DataContractJsonSerializer包含元素类型';s亚型

本文关键字:亚型 包含 元素 类型 DataContractJsonSerializer | 更新日期: 2023-09-27 18:21:13

我将使用DataContractJsonSerializer进行JSON序列化/反序列化。

我在JSON数组中有两种对象类型,希望将它们反序列化为相应的对象类型。具有以下类别定义

[DataContract]
public class Post {
    [DataMember(Name = "content")]
    public String Content { get; set; }
}
[DataContract]
public class User {
    [DataMember(Name = "user_name")]
    public String UserName { get; set; }
    [DataMember(Name = "email")]
    public String Email { get; set; }
}
[DataContract]
public class Container {
    [DataMember(Name="posts_and_objects")]
    public List<Object> PostsAndUsers { get; set; }
}

如何检测它们并将它们反序列化为相应的对象类型并存储在PostsAndUsers属性中?

DataContractJsonSerializer包含元素类型';s亚型

如果您指定了可以序列化和反序列化类Container的已知类型,请尝试以下代码:

protected static Stream GetStream<T>(T content)
{
    MemoryStream memoryStream = new MemoryStream();
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T), new []{typeof(Post), typeof(User)});
    serializer.WriteObject(memoryStream, content);
    memoryStream.Seek(0, SeekOrigin.Begin);
    return memoryStream;
}
protected static T GetObject<T>(Stream stream)
{
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T), new[] { typeof(Post), typeof(User) });
    return (T)serializer.ReadObject(stream);
}
static void Main(string[] args)
{
    var container = new Container {PostsAndUsers = new List<object>()};
    container.PostsAndUsers.Add(new Post{Content = "content1"});
    container.PostsAndUsers.Add(new User{UserName = "username1"});
    container.PostsAndUsers.Add(new Post { Content = "content2" });
    container.PostsAndUsers.Add(new User { UserName = "username2" });
    var stream = GetStream(container);
    var parsedContainer = GetObject<Container>(stream);
    foreach (var postsAndUser in parsedContainer.PostsAndUsers)
    {
        Post post;
        User user;
        if ((post = postsAndUser as Post) != null) 
        {
            // is post
        }
        else if ((user = postsAndUser as User) != null) 
        {
            // is user
        }
        else
        {
            throw new Exception("");
        }
    }
}