Dynamically deserialize json to any object passed in. FROM#

I am trying to make deserialize json into an object in C #. What I want to do is pass its type to any object and deserialize json into that specific object using the JSON.Net library. Here are the lines of code.

Object someObject1 = someObject; string result = await content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<someObject1.GetType()>(result); 

Exception thrown on last line

  operator '<' cannot be applied to operands of type 'method group' 

How to get data type in <> without C # complaint. What do I need to do to make this code work? And what knowledge do I lack?

+2
json c # serialization
Sep 04 '14 at 18:12
source share
3 answers

JsonConvert.DeserializeObject<T> requires a compile time type. You cannot pass it a type at runtime, how you want to do it (nothing but a List<T> declaration). You must either deserialize the generic json JObject (or dynamic), or create an instance of the object and populate it with json.

You can use the static method of PopulateObject (of course, if your object properties match the json you want to deserialize).

 JsonConvert.PopulateObject(result, someObject1 ); 
+2
Sep 04 '14 at 18:19
source share

You can ignore the general method and use dynamic :

 var myObj = (dynamic)JsonConvert.DeserializeObject(result); 

However, if objects are not of the same type, it will be difficult for you to distinguish between types and probably hit runtime errors.

0
Sep 04 '14 at 18:19
source share

This is the best way to populate object fields with JSON data.

This code belongs to the object itself as a method.

 public void PopulateFields(string jsonData) { var jsonGraph = JObject.Parse(jsonData); foreach (var prop in this.GetType().GetProperties()) { try { prop.SetValue(this, fields[prop.Name].ToObject(prop.PropertyType), null); } catch (Exception e) { // deal with the fact that the given // json does not contain that property } } 
0
Jun 30 '17 at 21:32
source share



All Articles