Insert Key value pair into existing JSON in C#

Viewed 7239

I have a json like below

{
    "name": "Ram",
    "Age": "25",
    "ContactDetails": {
        "MobNo": "1"
    }
}

Please suggest how to add

"Address": {
    "No": "123",
    "Street": "abc"
}

into ContactDetails

3 Answers

This should work (using Newtonsoft.Json)

var json = 
    @"{
        ""name"": ""Ram"",
        ""Age"": ""25"",
        ""ContactDetails"": {
            ""MobNo"": ""1""
        }
    }";

var jObject = JObject.Parse(json);
jObject["ContactDetails"]["Address"] = JObject.Parse(@"{""No"":""123"",""Street"":""abc""}");

var resultAsJsonString = jObject.ToString();

The result is:

{
  "name": "Ram",
  "Age": "25",
  "ContactDetails": {
    "MobNo": "1",
    "Address": {
      "No": "123",
      "Street": "abc"
    }
  }
}

One of the options would be use Newtonsoft's Json.NET to parse json into JObject, find needed token, and add property to it:

var jObj = JObject.Parse(jsonString);
var jObjToExtend = (JObject)jObj.SelectToken("$.ContactDetails");
jObjToExtend.Add("Address", JObject.FromObject(new { No = "123", Street = "abc" }));
Related