问题
If I have a JsValue
, which method shall I use to get values from the JsValue
: Json.fromJson
, as
, asOpt
and validate
?
回答1:
It depends on the level of error handling you want.
What as
, asOpt
, and validate
all have in common is that they will attempt to de-serialize a JsValue
into the type T
you specify, using whatever implicit Reads[T]
can be resolved. Where they differ is how they behave, and what types they return.
Let's say we're working with a class Foo
where we have an implicit Reads[Foo]
already defined.
as[Foo]
will simply try to convert a JsValue
into a Foo
, and if it fails, it will throw an exception. This is not a safe thing to do, as the only way to handle the error would be to catch the exception and deal with it, which you might not remember to do. JSON failing to map to a certain type is rarely an exceptional case, either--it happens all the time. as
should be used rarely, at most.
asOpt[Foo]
will try to convert a JsValue
into a Foo
, and if it fails, it will simply return None
. If it's successful, it will return the de-serialized value wrapped in Some
. This is much better than as
, since you are forced to confront the failure case (unless you do something silly like call .get
). The downside is, all of the errors are swallowed when converting the failure to None
, so you have no idea why it failed. If you don't care, using asOpt
is perfectly fine.
validate[Foo]
will try to convert a JsValue
into a Foo
, and will always return a JsResult[Foo]
. If the conversion is successful, it will be a JsSuccess[Foo]
that contains the de-serialized value. If it fails, it will be a JsError
that contains all of the error information such as what paths are missing and what types do not match what they are expected to be. You can use the fold
method on JsResult
to safely handle each case. For example:
js.validate[Foo].fold(
errors => /* Do something with the errors */ ,
foo => /* Do something with Foo */
)
Json.fromJson
does the exact same thing as JsValue#validate
. They both call the underlying Reads
to return a JsResult
.
来源:https://stackoverflow.com/questions/42727949/whats-the-difference-between-json-fromjson-as-asopt-and-validate