将字段添加到JSON数组中

我有一个带有这样的数组的JSON字符串:

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

我想在Packages数组中添加一个新字段,如:

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

现在我可以添加一个新字段但是在主对象中,我正在使用Json.NET库来完成这项工作,但似乎文档没有达到那个级别。

有没有人以前做过?

JObject实现了IDictionary。

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

尝试

 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