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

查看:118
本文介绍了DataContractJsonSerializer通用列表,其中包含元素类型的子类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm going to use DataContractJsonSerializer for JSON serialization/deserialization.

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

I have two object types in the JSON array and want them both to be deserialized into corresponding object types. Having the following class defnitions

[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 属性中?

how can I detect them and deserialize both into the corresponding object type and store in PostsAndUsers property?

推荐答案

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

If you specific the known types you can serialize and deserialize your class Container, try this code:

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

这篇关于DataContractJsonSerializer通用列表,其中包含元素类型的子类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆