JSON.NET deserialize JSON object stored as property

Viewed 7507

I have a JSON message to deserialize with a string property containing the JSON of another object. I have the following classes

public class Envelope
{
    public string Type { get; set; }
    public Message InnerMessage { get; set; }
}

public class Message
{
    public string From { get; set; }
    public string To { get; set; }
    public string Body { get; set; }
}

the JSON message I receive is in this format:

{
    Type : "send",
    InnerMessage : "{ From: \"sender\", To: \"receiver\", Body: \"test\" }"
}

note that InnerMessage contains the serialization of the Message class, not the JSON of the class.

If I keep the type of InnerMessage property to Message, the standard JSON.NET deserialization fails.

If I change the InnerMessage to string, the serialization works but after I need to deserialize again the content of InnerMessage to Message class:

Envelope envelope = JsonConvert.DeserializeObject<Envelope>(jsonMessage);
Message innerMessage = JsonConvert.DeserializeObject<Envelope>(envelope.InnerMessage);

There is some way to keep the InnerMessage property of Envelope to Message and tell JSON.NET to treat the string value to be deserialized automatically?

2 Answers
Related