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
1.4k views
in Technique[技术] by (71.8m points)

c# - How do you add a JToken to an JObject?

I'm trying to add a JSON object from some text to an existing JSON file using JSON.Net. For example if I have the JSON data as below:

  {
  "food": {
    "fruit": {
      "apple": {
        "colour": "red",
        "size": "small"
      },
      "orange": {
        "colour": "orange",
        "size": "large"
      }
    }
  }
}

I've been trying to do this like this:

var foodJsonObj = JObject.Parse(jsonText);
var bananaJson = JObject.Parse(@"{ ""banana"" : { ""colour"": ""yellow"", ""size"": ""medium""}}");
var bananaToken = bananaJson as JToken;
foodJsonObj["food"]["fruit"]["orange"].AddAfterSelf(bananaToken);

But this gives the error: "Newtonsoft.Json.Linq.JProperty cannot have multiple values."

I've actually tried a few different ways but can't seem to get anywhere. In my example what I really want to do is add the new item to "fruit". Please let me know if there is a better way of doing this or a simpler library to use.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I think you're getting confused about what can hold what in JSON.Net.

  • A JToken is a generic representation of a JSON value of any kind. It could be a string, object, array, property, etc.
  • A JProperty is a single JToken value paired with a name. It can only be added to a JObject, and its value cannot be another JProperty.
  • A JObject is a collection of JProperties. It cannot hold any other kind of JToken directly.

In your code, you are attempting to add a JObject (the one containing the "banana" data) to a JProperty ("orange") which already has a value (a JObject containing {"colour":"orange","size":"large"}). As you saw, this will result in an error.

What you really want to do is add a JProperty called "banana" to the JObject which contains the other fruit JProperties. Here is the revised code:

JObject foodJsonObj = JObject.Parse(jsonText);
JObject fruits = foodJsonObj["food"]["fruit"] as JObject;
fruits.Add("banana", JObject.Parse(@"{""colour"":""yellow"",""size"":""medium""}"));

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

...