How to add “undefined” to a JObject collection - where is JToken/JValue.Undefined?

大兔子大兔子 提交于 2019-12-25 18:55:23

问题


When using Json.NET, I am trying to create a JSON structure dynamically using the "JSON to LINQ" support.

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 */
}

How do I explicitly add a JToken/JValue for a JSON Undefined? How about for a JSON Null?


回答1:


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

Null is represented by new JValue((object)null), if I remember correctly.

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.




回答2:


jObject.Add(key, /* how to add "Undefined" token? */);

jObject.Add(key,JValue.CreateUndefined());



回答3:


According to this question, it doesn't support undefined.

After searching the docs, I found 2 references to "Undefined", but no explanation on how they might be used:

  • JsonConvert Fields
  • JTokenWriter.WriteUndefined Method


来源:https://stackoverflow.com/questions/21816238/how-to-add-undefined-to-a-jobject-collection-where-is-jtoken-jvalue-undefine

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