Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically deserialize json into any object passed in. c#

I'm trying to do is deserialize json into an object in c#. What I want to be able to do is pass any object get it's type and deserialize the json into that particular 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);

The last line throws an exception of

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

How do I get the data type in the <> without c# complaining. What do I have to do to make this code work? And what knowledge am I missing?

like image 303
raging_subs Avatar asked Oct 21 '25 23:10

raging_subs


1 Answers

JsonConvert.DeserializeObject<T> needs a compile-time type. You can't pass it a type in run time as you want to do in question (nothing different than declaring a List<T>). You should either deserialize to a generic json object JObject (or to dynamic) or you should create an instance of an object and fill it with json.

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

JsonConvert.PopulateObject(result, someObject1 );
like image 53
L.B Avatar answered Oct 23 '25 13:10

L.B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!