4

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?

1
  • For anyone finding this and reading it recently, The latest releases of System.Text.Json in .NET as well as NewtonSoft have overloads capable of taking a Type parameter at runtime. I'm using System.Text.Json now because it finally has everything I need for Json to POCO and back except for support for a hexadecimal type which, until recently the Json format has lacked. Commented Apr 19, 2024 at 15:11

4 Answers 4

6

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 );
Sign up to request clarification or add additional context in comments.

2 Comments

So if I pass in an Object someObject, but someObject is type someOtherObjectIMade then it'll populate someOtherObjectIMade's fields correct?
it does I just tested this.
3

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.

Comments

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);

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.