Add a field into JSON array

梦想的初衷 提交于 2019-12-20 04:04:46

问题


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?


回答1:


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



回答2:


Try

JObject root = (JObject) JsonConvert.DeserializeObject(File.ReadAllText("products.json"));
JArray packages = (JArray) root["Packages"];

JObject newItem = new JObject();
newItem["Name"] = "Cups";
// ...

packages.Add(newItem);

Console.WriteLine(root); // Prints new json


来源:https://stackoverflow.com/questions/39416530/add-a-field-into-json-array

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