DataContractJsonSerializer generic list containing element type's subtypes

柔情痞子 提交于 2020-01-04 02:53:13

问题


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

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; }
}

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


回答1:


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


来源:https://stackoverflow.com/questions/17487576/datacontractjsonserializer-generic-list-containing-element-types-subtypes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!