3

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

2
  • 3
    Deserialize the JSON string to an object, add the address details and serialize the object. Commented Jun 3, 2020 at 10:00
  • Welcome to StackOverflow! Have a look at learn.microsoft.com/en-us/dotnet/standard/serialization/… and post some sample code if you're stuck Commented Jun 3, 2020 at 10:03

3 Answers 3

4

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"
    }
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

one more query ,i need to insert some more values into existing jsonarray {"products":["a","b,"c","etc"]} , please suggest how to do it
Just use JArray: var jObject = JObject.Parse(json); var jArray = jObject["products"] as JArray; jArray.Add("new_product");
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" }));

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.