如何在C#中的JSON数组内修改JSON对象?

时间:2019-02-07 06:47:09

标签: c# json

这是我的Json数组

[
  {
   "gregdate": "06-03-2019",
   "maldate": "22-07-1194",
   "gregmonth": "March",
   "selected_status": "1"
  },
  {
   "gregdate": "04-05-2019",
   "maldate": "21-09-1194",
   "gregmonth": "May",
   "selected_status": "1"
  },
  {
   "gregdate": "03-06-2019",
   "maldate": "20-10-1194",
   "gregmonth": "June",
   "selected_status": "1"
  }
]

在此JSON数组中,我想将第二个JSON对象“ selected_status”的值“ 1”更改为“ 0”,而无需更改JSON对象的位置。

1 个答案:

答案 0 :(得分:3)

您需要先将对象数组转换为JArray,然后将其第二个对象属性从1更改为0,如

string json = "You json here";                            //Load your json

JArray jArray = JArray.Parse(json);                       //Parse it to JArray

var jObjects = jArray.ToObject<List<JObject>>();          //Get list of objects inside array

foreach (var obj in jObjects)                             //Loop through on a list
{
    if (jObjects.IndexOf(obj) == 1)                       //Get 2nd object from array
    {
        foreach (var prop in obj.Properties())            //List 2nd objects properties
        {
            if (prop.Name == "selected_status")           //Get desired property
                obj["selected_status"] = 0;               //Change its value
        }
    }
}

JArray outputArray = JArray.FromObject(jObjects);         //Output array

替代:

如布赖恩·罗杰斯(Brian Rogers)所建议的那样,您可以直接查询JArray来替换其特定的属性值,如

string json = "You json here";                            //Load your json

JArray jArray = JArray.Parse(json);                       //Parse it to JArray

jArray[1]["selected_status"] = "0";                       //Querying your array to get property of 2nd object

string outputJson = jArray.ToString();                    //Output json

输出:(来自调试器)

enter image description here