Ron Penton
Ron Penton

Reputation: 1521

Retrieve Dynamic class name from JSON.NET?

I'm receiving messages over a network using JSON.NET. The message format is somewhat dynamic, in that the messages will be represented by many different classes, each inheriting from a parent message. For example:

{
    MessageName: "MessageType1",
    Data1: 124,
    Data2: "Something"
}


{
    MessageName: "MessageType2",
    OtherData: "Some data",
    MoreData: "Even more",
    ANumber: 25
}

The problem I'm having is that in JSON.NET, I have no idea how to figure out the name of the class (MessageType1/MessageType2/etc) in order to deserialize it into an instance of the class without deserializing it twice. There's a few options I've considered; the one I'm currently using is to use a container class containing the message name and the actual json message serialized to string, but this seems wasteful.

Another method I've considered is deserializing into a string/string dictionary and then performing the population of the class on my own, which seems messy and unnecessary considering JSON.NET can do that for me... as long as I know the class first.

I'm really hoping there's an easy way to have JSON.NET figure out a class name by examining the MessageName property and then continue to populate a class after examining that one property.

Thanks for the help!

Upvotes: 1

Views: 352

Answers (1)

DrKoch
DrKoch

Reputation: 9772

JSON can deserialize into a well known class only. You need to specify the data layout (i.e. the class/type)

There are two alternatives:

1.) go one level deeper. Use the JSON Token parser to read the tokens from your JSON stream and act based on the tokens you find.

2.) as you suggested: Use a class layout flexible enough to hold all your possible variations like a key/value dictionary.

Upvotes: 1

Related Questions