0

尝试从互联网反序列化 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; }
}
4

1 回答 1

1

我想出了一种解析它的方法。通过使用 JsonConverter。这是我的转换器类:

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);
于 2013-05-16T22:56:43.743 回答