如何使用同一个类反序列化两个响应?
本文关键字:两个 响应 何使用 同一个 反序列化 | 更新日期: 2023-09-27 18:15:51
我目前从一个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
}
我如何使用相同的类(需要改变什么)来反序列化两种格式,或者这是不可能的,我需要每个类?
你可以这样做:
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; }
...
}
[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);