0

I´m using C# MVC and have the following JSON:

MessageType: "Type1"

MessageData: {{Name: "Jonas"}, Phones: [{ Fixed: "12345", Mobile: "45678" }], Addresses: [{ Home: "ababa"} ... ], { HasId: "Yes }, ... }

The MessageData will contain different data depending on MessageType.

What I need is to deserialize it into the following C# structure:

public class AjaxMsg 
{
    public string MessageType { get; set; }
    public object MesssageData { get; set; }
}

I´m using the native serialization during the POST from client, but I only get the MessageType data.

Also, the code:

var msgDataString = MessageData.ToString()

returns "System.Object"

How can I get the MessageData accordingly as an object format ?

tereško
  • 58,060
  • 25
  • 98
  • 150
Mendes
  • 17,489
  • 35
  • 150
  • 263
  • 1
    Possible duplicate of https://stackoverflow.com/questions/19307752/deserializing-polymorphic-json-classes-without-type-information-using-json-net or http://stackoverflow.com/questions/5186973/json-serialization-of-array-with-polymorphic-objects. – dbc Dec 11 '14 at 00:45

2 Answers2

0

You can use JSON.NET's ToObject method:

JObject Data = Message.MessageData; 
Type type = Message.MessageType;
object obj = Data.ToObject(type); // if you dont know the type in compile time

MyType obj2 = Data.ToObject<MyType>(); // if you know the type in compile time
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
0

Create a wrapper class to deserialize :

[Serializable]
public class AjaxMsg
{
    [DataMember]
    public string MessageType { get; set; }

    [DataMember]
    public object MessageData { get; set; }
}

public class Data
{
    public IList< AjaxMsg> list {get;set;}
}

var obj = JsonConvert<Data>(json);
Deependra Singh
  • 161
  • 2
  • 8