简体   繁体   中英

Add a JToken to a specific JsonPath in a JObject

I have a JObject that looks like this..

{
    "address": [
        {
            "addressLine1": "123",
            "addressLine2": "124"
        },
        {
            "addressLine1": "123",
            "addressLine2": "144"
        }
    ]
}

for JsonPath address[2] , I want to add the following JObject to the address array.

{
     "addressLine1": "123",
     "addressLine2": "144"
}

I want to do something like json.TryAdd(jsonPath, value);

If there was an object at index 2 i would have easily done

var token = json.SelectToken(jsonPath);
if (token != null && token .Type != JTokenType.Null)
{
      token .Replace(value);
}

but since that index does not exist I'll get null as the value of token

As we mentioned on comment section, you can not add/replace item to index if index does not exist. In that case you need to add item as a new member of JArray instead, or you can use Insert to add item at the specified index :

JObject value = new JObject();
value.Add("addressLine1", "123");
value.Add("addressLine2", "144");

JObject o = JObject.Parse(json);
int index = 2;
JToken token = o.SelectToken("address[" + index + "]");
if (token != null && token.Type != JTokenType.Null)
{
    token.Replace(value);
}
else //If index does not exist than add to Array
{
    JArray jsonArray = (JArray)o["address"];
    jsonArray.Add(value);
    //jsonArray.Insert(index, value); Or you can use Insert

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM