Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I got a JSON string with an array like this:

 {
  "Id": 123,
  "Username": "Sr. X",
  "Packages": [
    {
      "Name": "Cups",
      "SupplierId": 1,
      "ProviderGroupId": 575,
      "SupplierName": "Foo Cups"
    },
    {
      "Name": "Pins",
      "SupplierId": 5,
      "ProviderGroupId": 1082,
      "SupplierName": "Foo Pins"
    }
  ]
}

and I want to add a new field into Packages array like:

"Packages": [
    {
      "Name": "Cups",
      "SupplierId": 1,
      "ProviderGroupId": 575,
      "SupplierName": "Foo Cups",
      "New Field": "Value"
    },...

Right now I can add a new field but in the main object, I'm using Json.NET library to do the job, but it seems that the documentation doesn't reach that level.

Have any one of you done it before?

See Question&Answers more detail:os

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

1 Answer

JObject implemets IDictionary.

var jObj = JObject.Parse(json);
foreach(var item in jObj["Packages"])
{
    item["New Field"] = "Value";
}
var newjson = jObj.ToString(Newtonsoft.Json.Formatting.Indented);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...