JToken.ToObject< T>()与JToken.Value< T>()之间的差异 [英] Difference between JToken.ToObject<T>() vs JToken.Value<T>()

查看:306
本文介绍了JToken.ToObject< T>()与JToken.Value< T>()之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JToken.ToObject<T>()方法和JToken.Value<T>()扩展方法(不带key参数的扩展方法)之间有什么区别?

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. ToObject<T>() 反序列化操作.它构造一个 JsonSerializer 并使用它反序列化当前JToken为所需的类型.这样,令牌可以是任何东西(JSON数组,JSON对象或JSON基本值),并且序列化程序将使用反射尝试通过使用 JTokenReader .

  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.

在编写通用代码(输入令牌和输出类型可以是任何东西)时,此方法很有用.这是从JToken创建c#对象的最通用且最安全的方法.

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>) 转换/广播操作.它尝试通过调用value 转换为目标类型. changetype"rel =" nofollow noreferrer> Convert.ChangeType() (以及处理一些特殊情况).

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

当您知道您的JToken实际上是 Value 转换为特定的,必需的.Net基本类型.例如,如果JValue可能包含long或数字字符串,则可以将其转换为intdecimaldouble.如果它可能包含DateTime ISO 8601 格式的字符串,则可以将其转换到DateTime.而且任何原始JSON值都可以始终转换为字符串.

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.

虽然此方法不及ToObject<T>()通用,但由于在序列化反序列化基元时,序列化程序会在内部调用相同的转换方法,因此在转换基元值时性能会更高.

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.

这篇关于JToken.ToObject&lt; T&gt;()与JToken.Value&lt; T&gt;()之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆