Search code examples
c#jsonserializationdynamicjavascriptserializer

Convert deserialized dynamic Json to strongly typed classes


I have a message formatter class that needs to be able to serialize and deserialize JSON messages. This centralized class will be called by a separate client that sends and receives messages from a server. The problem I'm running into is I don't know what class type that I'll be receiving on a response message. The serialization part is fine, code below.

public override object Serialize(object message)
{
   return new JavaScriptSerializer().Serialize(message);
}

The closest I can get is to deserialize using a dynamic operator like so.

public override object Deserialize(object message)
{
   return new JavaScriptSerializer().Deserialize<dynamic>(message.ToString());
}

But I really want to return is the actual class with the properties within the class filled with the data from the response message. I've played with GetType and other options like

return new JavaScriptSerializer().Deserialize(message.ToString(), typeof(Some Class));

But nothing I try will work without knowing the response class in advance. I've thought about storing the class name in the Json object and using an Activator to spin it up, but is there a cleaner way to do this?


Solution

  • Instead of using JavaScriptSerializer you can use JSON.NET and embed the type information during serialisation. Please see this for detail: http://www.newtonsoft.com/json/help/html/SerializeTypeNameHandling.htm

    Then you can extract the type information from Json string during deserialisation as follows: Json.Net - Get type name when deserializing to JObject