如何使用同一个类反序列化两个响应?

时间:2014-08-01 04:59:02

标签: c# json .net-4.5

我目前正在从这样的API中获取数据:

{
    "messages": [
        ...somedata...
    ],
    "timestamp": 123456,
    "request": 1
}

我可以轻松地反序列化为:

public class Data
{
    [JsonProperty("messages")]
    public List<...> Messages { get; set; }
    [JsonProperty("timestamp")]
    public int Timestamp { get; set; }
    [JsonProperty("request")]
    public int RequestsLeft { get; set; }
}

然而,相同的API有时也会在属性上返回带有短名称的数据,如下所示:

{
    "m": [
        ...somedata...
    ],
    "t": 123456,
    "r": 1
}

如何使用相同的类(需要更改的内容)来反序列化这两种格式,或者这是不可能的,我需要为每个类创建一个类?

2 个答案:

答案 0 :(得分:1)

你可以这样做:

public class Data
{
  [JsonProperty("messages")]
  public List<...> Messages { get; set; }

  [JsonProperty("m")]
  public List<...> m_list { 
    get{ return Messages; }
    set{ Messages = value; }
  }

  [JsonProperty("timestamp")]
  public int Timestamp { get; set; }

  ... 

  [JsonProperty("request")]
  public int RequestsLeft { get; set; }

  ...
}

答案 1 :(得分:1)

[DataContractAttribute]
public class Data
{
    private string[] messages;

    [DataMember(Name = "messages")]
    public string[] Messages
    {
        get
        {
            return messages;
        }

        set
        {
            messages = value;
        }
    }

    [DataMember(Name = "m")]
    public string[] AlternativeMessages
    {
        get
        {
            return messages;
        }

        set
        {
            messages = value;
        }
    }

    [DataMember(Name = "timestamp")]
    public int Timestamp { get; set; }

    [DataMember(Name = "request")]
    public int Request { get; set; }
}

public class JsonUtils
{
    public static T JsonDeserialize<T>(string jsonString)
    {
        var ser = new DataContractJsonSerializer(typeof(T));
        var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
        T obj = (T)ser.ReadObject(ms);
        return obj;
    }
}




var value = "{ \"m\": [\"Hi!\", \"Prix\"], \"timestamp\": 123456, \"request\": 1 }";

var data = JsonHandler.JsonDeserialize<Data>(value);