1

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!

1
  • You could use dynamic keyword to deserialize into a dynamic object and then traverse the properties to get the MessageName. Commented Mar 16, 2015 at 16:39

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I ended up using a reader to read in the MessageName token, then using reflection to get the type, and then finally used the JSONConverter to fill in the object. A bit more work than I really wanted to do, but it works, at least, without resorting to some insane double-encoding transmission format.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.