问题描述
作为我的问题的后续行动:JSON.NET:从 JProperty 值获取 JObject ...
As a follow up to my question here:JSON.NET: Obtain JObject from JProperty Value ...
我阅读了链接并消化了上述评论和建议.现在我想知道:为什么没有直接"(即简单)方法将 JProperty 对象的值转换为 JObject 有充分的理由吗?获得 JToken 似乎需要做很多工作,然后必须构造 if 语句等.这不是抱怨额外的工作;而是承认我仍然认为我不了解JToken的真正目的.有一次,所有 FedEx 包裹首先被路由到孟菲斯:似乎所有对象都可以/应该先到 JToken,然后再打包到实际的目标对象类型.这是一种思考方式吗?
I read links and digested the above comments and advice. Now I wonder: Is there a good reason why there is no "direct" (i.e., easy) way to turn the Value of a JProperty object into a JObject? It seems like a lot of work to get to a JToken and then have to construct if statements, etc. This isn't to complain about the extra work; rather, it's to admit that I still think I don't understand the true purpose of JToken. At one time, all FedEx packages first routed to Memphis: It seems that all objects can/should go to JToken first then be parceled to the actual target object type. Is that a way to think about it?
换句话说,使用 JToken 是否有充分的理由——或者仅仅是因为许多其他函数返回一个 JToken,然后您必须处理它?JSON.NET 手册提供了将 JToken 转换为其他类型的方法 (http://www.newtonsoft.com/json/help/html/Operators_T_Newtonsoft_Json_Linq_JToken.htm)但没有提到从 JToken 到 JObject...
In other words, is there ever a good reason to use JToken--or is it just that so many other functions return a JToken and then you have to just deal with that? The JSON.NET manual gives ways to cast JToken to other types (http://www.newtonsoft.com/json/help/html/Operators_T_Newtonsoft_Json_Linq_JToken.htm) but doesn't mention going from JToken to JObject...
我发现 JObject 通常是我想要使用的,以便使用 JSON 并将 JSON 映射到我的 .NET 类并再次返回 - 以及执行许多其他操作.我仍然想知道使用 JToken 对象的令人信服的理由是什么?
I find that JObject is usually what I want to have in order to work with JSON and to map from JSON to my .NET classes and back again--as well as doing a host of other operations. I still wonder what is the compelling reason to ever use a JToken object?
推荐答案
从标准构建JSON属于以下五种令牌:
From the standard, JSON is built out of the following five types of token:
- 对象:一组无序的名称/值对.
- 数组:值的有序集合.
- value:双引号中的字符串,或数字,或
true
或false
或null
,或对象或数组.这些结构可以嵌套. - 字符串
- 号码.
- object: an unordered set of name/value pairs.
- array: an ordered collection of values.
- value: a string in double quotes, or a number, or
true
orfalse
ornull
, or an object or an array. These structures can be nested. - string
- number.
JToken
是一个抽象基础代表这些可能标记中的任何一个的类.如果你有一些 JSON 并且事先不知道里面可能是什么,你可以使用 JToken.Parse()
只要 JSON 格式正确就可以得到结果.JObject.Parse()
和 JArray.Parse()
如果 rootJSON 令牌不是预期的类型.并且没有 JValue.Parse()
解析一个你知道代表原子"值的 JSON 字符串,在这种情况下需要使用 JToken.Parse()
.
同样,JToken.FromObject()
可用于将任何类型的 c# 对象序列化为 JToken
层次结构,而无需事先知道生成的 JSON 类型.这可能很有用,例如在编写通用序列化相关代码时.
Similarly, JToken.FromObject()
may be used to serialize any sort of c# object to a JToken
hierarchy without needing to know in advance the resulting JSON type. This can be useful e.g. when writing generic serialization-related code.
这篇关于JSON.NET:为什么要使用 JToken——永远?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!