簡體   English   中英

如何在 C# 中修改 JSON 數組中的 JSON 對象?

[英]How to Modify JSON object inside JSON array in c#?

這是我的 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 對象的位置的情況下將第二個 JSON 對象“selected_status”值“1”更改為“0”。

您需要先將對象數組轉換為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

輸出:(來自調試器)

在此處輸入圖片說明

這個問題幫助我弄清楚了一些事情 - 所以這就是我想出的。 我猜 json 是一個示例,需要的是更改特定日期的狀態,而不僅僅是第二個元素。 至少這就是我一直在尋找的。 這更具動態性,您不必擔心元素的位置。

string newJson = "";

if (SwitchStatus(jsonString, "04-05-2019", "0", out newJson))
{
    Console.Write(newJson);
}
else 
{ 
    Console.WriteLine("Date Not Found"); 
}

Console.ReadLine();

static bool SwitchStatus(string jsonString, string searchBy, string switchTo, out string output)
{
    dynamic jsonObj = JsonConvert.DeserializeObject(jsonString);

    JToken status = jsonObj.SelectToken($"$..[?(@.gregdate == '{searchBy}')].selected_status");
    if (status != null)
    {
        status.Replace(switchTo);
        output = JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);       
    }
    else
    {
        output = jsonString;
    }

    return status != null;

}

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM