包含元素类型的DataContractJsonSerializer通用列表'的子类型[英] DataContractJsonSerializer generic list containing element type's subtypes

本文是小编为大家收集整理的关于包含元素类型的DataContractJsonSerializer通用列表'的子类型的处理方法,想解了包含元素类型的DataContractJsonSerializer通用列表'的子类型的问题怎么解决?包含元素类型的DataContractJsonSerializer通用列表'的子类型问题的解决办法?那么可以参考本文帮助大家快速定位并解决问题。

问题描述

我将使用 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 属性中?

推荐答案

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

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("");
        }
    }
}

本文地址:https://www.itbaoku.cn/post/1794038.html