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

c# - Add a field into JSON array

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

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

1 Reply

0 votes
by (71.8m points)

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

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

1.4m articles

1.4m replys

5 comments

57.0k users

...