如何添加“未定义"到JObject集合-JToken/JValue.Undefined在哪里? [英] How to add "undefined" to a JObject collection - where is JToken/JValue.Undefined?
问题描述
使用Json.NET时,我尝试使用动态创建JSON结构. JSON到LINQ" 支持.
When using Json.NET, I am trying to create a JSON structure dynamically using the "JSON to LINQ" support.
在下面,jObject
是 JObject 和JObject .Add需要(字符串, JToken ).但是,我找不到如何添加未定义或Null令牌的方法,也无法找到如何使用适当的Null/Undefined类型创建JValues.
In the following, jObject
is a JObject and JObject.Add takes (string, JToken). However, I cannot find out how to add either an Undefined or a Null token - nor can I find out how to create JValues with the appropriate Null/Undefined type.
string value = GetValue();
if (value == "undefined") {
jObject.Add(key, /* how to add "Undefined" token? */);
} else if (value == "null") {
jObject.Add(key, /* how to add "Null" token? */);
} else {
jObject.Add(key, new JToken(value)); /* String value/token */
}
如何为JSON未定义显式添加JToken/JValue? JSON Null怎么样?
How do I explicitly add a JToken/JValue for a JSON Undefined? How about for a JSON Null?
推荐答案
将属性设置为 undefined 在功能上等同于完全不设置该属性.因此,如果属性未定义,则只需不向JObject
添加任何属性. (这可能就是JSON不支持undefined
的原因-它是完全多余的.)
Setting a property to undefined is functionally equivalent to not setting the property at all. So, if the property is undefined, you just don't add any properties to your JObject
. (And this is probably the reason why undefined
isn't supported by JSON — it's completely redundant.)
空用new JValue((object)null)
表示.
P.S.使用代码,您将无法分辨字符串"undefined"
和undefined
值之间以及"null"
和null
之间的区别.您可能需要重新考虑您的设计.
P.S. With your code, you won't be able to tell the difference between a string "undefined"
and an undefined
value, as well as between "null"
and null
. You probably need to rethink your design.
这篇关于如何添加“未定义"到JObject集合-JToken/JValue.Undefined在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!