0

I am working on building a re-usable function to deserialize a JSON string.

The JSON deserialization routines need an object type(jsonTestObject). This all works as expected.

  // serialize json to object

  jsonTestObject testO = new jsonTestObject();
  testO = Newtonsoft.Json.JsonConvert.DeserializeObject<jsonTestObject>(jsonString);

When I try to wrap this in a re-usable function to deserialize "any" object type I send, I run into issues. I am not sure how to pass the object type as a parameter to the function as I cant strongly type it.

I want to send "any" object type to my function and cast the result to my desired object type (As I will know what object type I am expecting when making the call.)

I don't want to hardcode a separate function for all classes that I want to serialize/deserialize.

Here is what I have that is not working...

    JSONdeserialize(string jSONstring,Type t)
    {
        object newObject;
        
        // deserialize object based on the original object type that was passed in.
        newObject = JsonConvert.DeserializeObject<t>(jSONstring); //ERROR LINE
       
        return newObject;
    }

jsonTestObject jsonObject = new jsonTestObject();
object o = JSONdeserialize(jsonString, jsonObject.GetType());

jsonObject = (jsonTestObject)o;

ERROR: "'t' is a variable but is used like a type"

Louis van Tonder
  • 3,664
  • 3
  • 31
  • 62

2 Answers2

3
newObject = JsonConvert.DeserializeObject(jSONstring, t);
Roman Ryzhiy
  • 1,540
  • 8
  • 5
1

The code can be written in both the way.

public void JSONdeserialize<T>(string jSONstring)
{
   return JsonConvert.DeserializeObject<T>(jSONstring); 
}

jsonTestObject jsonObject = new jsonTestObject();
object o = JSONdeserialize<jsonTestObject>(jsonString);

jsonObject = (jsonTestObject)o;

or

public void JSONdeserialize(string jSONstring, Type type)
{
   return JsonConvert.DeserializeObject(jSONstring, type); 
}

jsonTestObject jsonObject = new jsonTestObject();
object o = JSONdeserialize(jsonString, typeof(jsonTestObject));

jsonObject = (jsonTestObject)o;
Vimal CK
  • 3,543
  • 1
  • 26
  • 47