4

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"
    }
} 
Sachin
  • 459
  • 1
  • 7
  • 22

2 Answers2

0

Using ExpandoObject

You can try using the ExpandoObject. This way, you can add/edit properties on the expanding object and then serialize again and have the extended json object.

var obj = JsonConvert.DeserializeObject<ExpandoObject>(jsonText, new ExpandoObjectConverter());

https://learn.microsoft.com/en-us/dotnet/api/system.dynamic.expandoobject?view=netcore-3.1

Represents an object whose members can be dynamically added and removed at run time.

Using Json.Text

Guessing that's your approach. Check How to add property in existing json using System.Text.Json library? for solutions.

Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61
0

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