Reputation: 423
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
Upvotes: 0
Views: 1101
Reputation: 5370
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
}
Upvotes: 1