Home > Software design >  Deserialize JSON to a dynamic object or a class in C#
Deserialize JSON to a dynamic object or a class in C#

Time:12-21

I am trying to deserialize JSON into an object so I can add it to elastic search. JSON can be of many different object types in the project so I would like the function to be dynamic.

First I am serializing the Data that I get from EF Core context

var serializedObject = JsonConvert.SerializeObject(document, Formatting.None,
                       new JsonSerializerSettings()
                       {
                           ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                       });

Next I would like to deserialize to an object. For example if I have

public class EValues 
{
    public dynamic values { get; set; }
}

var test =  JsonConvert.DeserializeObject<EValues>(serializedObject.ToString());

I would like the JSON to be deserialized to the below:

{
   "values":{
      "StudentId":"60712555-ff1d-4a3e-8c81-08d9c2fc4423",
      "Student":{
         "Name":"string",
         "Country":"string",
         "Street":"string"
      }
   }
}

The serializedObject JSON I am actually trying to deserialize:

{
   "StudentId":"60712555-ff1d-4a3e-8c81-08d9c2fc4423",
   "Student":{
      "Name":"string",
      "Country":"string",
      "Street":"string"
   }
}

CodePudding user response:

You can just do:

var test = new EValues { 
    values = JsonConvert.DeserializeObject<dynamic>(serializedObject) 
};

The JSON that would correspond to EValues would have an extra level of nesting { "values" : {} } not present in your serializedObject JSON.

  • Related