Difference between JToken.ToObject<T>() vs JToken.Value<T>()

别来无恙 提交于 2021-01-27 06:37:50

问题


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:

  1. 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.

  2. 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 the JValue might contain a long or numeric string, you could convert it to an int, a decimal or a double. If it might contain a DateTime or a string in ISO 8601 format, you could convert it to a DateTime. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!