Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

c# - How to add "undefined" to a JObject collection - where is JToken/JValue.Undefined?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...