Search code examples
c#json.netserializationjson-deserialization

How to update the element value inside serialized dynamic JSON


I have a requirement in .net(C#) where I need to send the dynamic type of object inside the JSON and need to update it another API and send it again to another API for processing. I am having difficulty de-serializing it to dynamic type to update the one of the property.

I am able to get the values with "RootElement.GetProperty()" but could not fins anything for setting the values inside the JSON.

Appreciate the help.

Example of JSON structure which is getting passed to .net core api:

 {
  "TaskId": "24332",
  "Code": "Sample_code",
      "Type": 1,
      "Name": "New Product",
      "Params": {
        "Year": "2020",
    "Filter": "LTH"
    }
} 

Solution

  • I would suggest to use Newtonsoft's native objects JObject, JArray or JToken.

    For example, in your case, if you want to modify the Params property, you only have to access the object and add/edit the property:

    string json = @"{'TaskId':'24332','Code':'Sample_code','Type':1,'Name':'New Product','Params':{'Year':'2020','Filter':'LTH'}}";
    
    JObject jObject = JsonConvert.DeserializeObject<JObject>(json);
    
    if (jObject["Params"] is JObject p) {
        p.Add("ProductType", "Battery");
    }
    
    string newJson = JsonConvert.SerializeObject(jObject);