问题
What is the difference between the JToken.ToObject<T>()
method and the JToken.Value<T>()
extension method (the one without the key
parameter)?
var jToken = JToken.Parse("123");
var toObjectStrResult = jToken.ToObject<string>();
var valueStrResult = jToken.Value<string>();
// toObjectStrResult == valueStrResult == "123"
var toObjectLongResult = jToken.ToObject<long>();
var valueLongResult = jToken.Value<long>();
// toObjectLongResult == valueLongResult == 123L
回答1:
The difference is as follows:
ToObject<T>() is a deserialization operation. It constructs a JsonSerializer and uses it to deserialize the current
JToken
to the desired type. As such the token could be anything (a JSON array, a JSON object, or a JSON primitive value) and the serializer will, using reflection, try to deserialize the token to the desired type by reading through its contents with a JTokenReader.This method is useful when writing generic code where the input token and output type could be anything. It is the most general and fail-safe way to create a c# object from a
JToken
.Extensions.Value<U>(IEnumerable<JToken>) is a conversion/casting operation. It attempts to convert the value of the current token to the target type by invoking Convert.ChangeType() (as well as handling a few special cases).
This method is useful when you know your
JToken
is, in fact, a JValue and you want to convert its Value to a specific, required .Net primitive type. For instance, if theJValue
might contain along
or numeric string, you could convert it to anint
, adecimal
or adouble
. If it might contain aDateTime
or a string in ISO 8601 format, you could convert it to aDateTime
. And any primitive JSON value can always converted to a string.While this method is less general than
ToObject<T>()
it will be more performant in converting primitive values since the serializer invokes the same conversion methods internally when deserializing a primitive.
来源:https://stackoverflow.com/questions/58188277/difference-between-jtoken-toobjectt-vs-jtoken-valuet