简体   繁体   中英

Deserialize JSON to a dynamic object or a class in C#

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM