0

Ok i dont even know if the title makes any sense, but i am having difficulty describing what i need to do. So take a look at the example plz.

I am doing this:

(SportsParent)JsonConvert.DeserializeObject<SportsParent>(jsonObj);

But what if i wanted to have the class name "SportsParent" stored in a string, and create a Type object from it. And then use that Type object for casting.

Something like that:

Type type = Type.GetType("myNanespace.SportsParent");
(type )JsonConvert.DeserializeObject<type >(jsonObj);

Thank you.

  • 2
    If you 'don't know' the type at compile time, you cannot access the properties at compile time without reflection. (disregarding dynamic). I think you're just looking for `object obj = JsonConvert.DeserializeObject(value, type);` – Silvermind Jul 01 '14 at 10:47

1 Answers1

0

There is an overload of JsonConvert.DeserializeObject that accepts a Type. Try this:

string typeName = "myNamespace.SportsParent";

Type type = Type.GetType(typeName);
object obj = JsonConvert.DeserializeObject(jsonObj, type);

Then, later in your code...

if (obj is SportsParent)
{
    SportsParent sp = (SportsParent) obj;
    // do something with sp here
}
else if (obj is SomeOtherType)
{
    SomeOtherType sot = (SomeOtherType) obj;
    // handle other type
}
else
{
    throw new Exception("Unexpected type: " + obj.GetType().FullName);
}
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
  • Thank you both for your answers. This is actually solving half of the problem. The other half is that i ll still have to manually cast the object back to SportParent. But the correct Type, is the Type that is held by the "type" object, and that Type may not be SpostsParent. – user3757324 Jul 01 '14 at 14:25
  • Since you don't know the type at compile time, of course you will have to cast it at run time in order to use it. That is the case any time you're working with an unknown type. But surely it is one of a small set of types that you are expecting, no? If so, then you can check the type at the point you need to use it and then cast it accordingly. If the type can truly be anything at all, then you will need to use reflection to handle it. – Brian Rogers Jul 01 '14 at 15:27