3

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?

Brian Rogers
  • 110,187
  • 27
  • 262
  • 261
raging_subs
  • 839
  • 2
  • 11
  • 27

4 Answers4

5

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 );
L.B
  • 106,644
  • 18
  • 163
  • 208
2

You can ignore the generic method and use dynamic:

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

However, if the objects aren't of the same type you'll have a hard time distinguishing between the types and probably hit runtime errors.

Dave Zych
  • 20,491
  • 7
  • 49
  • 65
1

For anyone bumping into this problem, the newer versions of Newtonsoft JSON have an overload that takes a type as a second argument and where you can pass a dynamic value without jumping through any hoops:

var myObj = JsonConvert.DeserializeObject(string serializedObject, Type deserializedType);
0

This is the best way to populate an object's fields given JSON data.

This code belongs in 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
        }
}