尝试从互联网反序列化json时遇到问题。 但我不知道如何正确地反序列化一个数组中的差异类型。 怎么做正确? 抱歉我的英语很差。
这是json:
{
"timestamp":"2012-06-19T08:00:49Z",
"items":[
{
"type":"text",
"content":"etc"
},
{
"type":"video",
"url":"etc"
}
...
]
}
我的代码:
public interface IPost
{
string PostType { get; set; }
}
public class TextPost : IPost
{
[JsonProperty("type")]
public string PostType { get; set; }
[JsonProperty("content")]
public string Content { get; set; }
}
public class VideoPost : IPost
{
[JsonProperty("type")]
public string PostType { get; set; }
[JsonProperty("url")]
public string Url { get; set; }
}
public class ResponseData
{
[JsonProperty("timestamp")]
public string Timestamp { get; set; }
[JsonProperty("items")]
public List<IPost> Items { get; set; }
}
答案 0 :(得分:1)
我找到了解析它的方法。通过使用JsonConverter。 这是我的Converter类:
public class PostsConverter : JsonConverter
{
// Create an instance
protected IPost Create(JObject jObject)
{
if (PostType("Text", jObject)) return new Text();
if (PostType("Video", jObject)) return new Video();
throw new Exception("Error");
}
public override bool CanConvert(Type objectType)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var list = new List<IPost>();
var arr = JArray.Load(reader);
foreach (var item in arr)
{
var obj = JObject.Load(item.CreateReader());
// Create target object based on JObject
var post = Create(obj);
// Populate the object properties
serializer.Populate(obj.CreateReader(), post);
list.Add(post);
}
return list;
}
private bool PostType(string type, JObject jObject)
{
return jObject["PostType"] != null && jObject["PostType"].Value<string>() == type;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
// I don't need serialize object
throw new NotImplementedException();
}
}
响应类:
public class ResponseData
{
[JsonProperty("timestamp")]
public string Timestamp { get; set; }
[JsonConverter(typeof(PostsConverter))]
[JsonProperty("items")]
public List<IPost> Items { get; set; }
}
现在我可以解析它了:
var myData = JsonConvert.DeserializeObject<ResponseData>(json);