Roadside Romeozz
Roadside Romeozz

Reputation: 83

Insert Key value pair into existing JSON in C#

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

Upvotes: 3

Views: 15292

Answers (3)

Guru Stron
Guru Stron

Reputation: 141575

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" }));

Upvotes: 1

Tomas Chabada
Tomas Chabada

Reputation: 3019

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"
    }
  }
}

Upvotes: 4

Gowthaman
Gowthaman

Reputation: 40

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

Upvotes: 0

Related Questions