Craig
Craig

Reputation: 1940

Can Json.Net cast a deserialized object to the type embedded in the Json?

Context: I'm serializing data into a message queue. The message queue will accept heterogeneous types, that need to be deserialized by the receiver.

Problem: Normally when deserializing, I'd use code like: JsonConvert.DeserializeObject<Type>(object); However, because the types are heterogeneous, I won't trivially know the desired type ahead of time.

I know I can use TypeNameHandling to embed the type in the JSON, but when calling DeserializeObject, I still don't get a strongly typed result (as in, the returned object isn't cast to the embedded Type already).

Question: Can Json.Net cast a deserialized object to the type embedded in the Json? If not, is my best option to get the type from the JSON and then call DeserializeObject so the object can be cast?

Upvotes: 3

Views: 383

Answers (1)

Risto M
Risto M

Reputation: 3009

You can embed Type (class) name to your data. When deserializing, you can use little bit of reflection and JsonConvert.DeserializeObject(string, Type):

string typeName; //Got from message
string json; //Got from message
Type type = Type.GetType($"Namespace.{typeName}, MyAssembly");
var obj = JsonConvert.DeserializeObject(json, type);

Upvotes: 4

Related Questions