将字段添加到JSON数组 [英] Add a field into JSON array

查看:131
本文介绍了将字段添加到JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了一个带有如下数组的JSON字符串:

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"
    }
  ]
}

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

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"
    },...

现在我可以添加一个新字段,但是在主对象中,我正在使用Json.NET库来完成这项工作,但是看来文档还没有达到这个水平.

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.

你们中有人做过吗?

推荐答案

JObject实现IDictionary.

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

这篇关于将字段添加到JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆