2

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

Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137
Roadside Romeozz
  • 73
  • 1
  • 1
  • 8
  • 3
    Deserialize the JSON string to an object, add the address details and serialize the object. – brz Jun 03 '20 at 10:00
  • Welcome to StackOverflow! Have a look at https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to and post some sample code if you're stuck – Bernard Vander Beken Jun 03 '20 at 10:03

3 Answers3

3

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"
    }
  }
}
Tomas Chabada
  • 2,869
  • 1
  • 17
  • 18
  • one more query ,i need to insert some more values into existing jsonarray {"products":["a","b,"c","etc"]} , please suggest how to do it – Roadside Romeozz Jun 03 '20 at 11:41
  • Just use JArray: `var jObject = JObject.Parse(json); var jArray = jObject["products"] as JArray; jArray.Add("new_product");` – Tomas Chabada Jun 03 '20 at 11:55
1

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" }));
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
0

Just Deserialize the JSON into object, then insert the value that you need to insert to it. Then, Serialize the object into JSON.

Reference: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to

Gowthaman
  • 40
  • 5