问题描述
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
推荐答案
区别如下:
-
ToObject<T>()
是反序列化操作.它构造一个JsonSerializer
并使用它反序列化当前JToken
为所需的类型.这样,令牌可以是任何东西(JSON数组,JSON对象或JSON基本值),并且序列化程序将使用反射尝试通过使用JTokenReader
.
ToObject<T>()
is a deserialization operation. It constructs aJsonSerializer
and uses it to deserialize the currentJToken
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 aJTokenReader
.
在编写通用代码(输入令牌和输出类型可以是任何东西)时,此方法很有用.这是从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
实际上是 JValue
,并且您想要转换其 Value
转换为特定的,必需的.Net基本类型.例如,如果JValue
可能包含long
或数字字符串,则可以将其转换为int
,decimal
或double
.如果它可能包含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< T>()与JToken.Value< T>()之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!