gpt4 book ai didi

c# - DataContractJsonSerializer 泛型列表包含元素类型的子类型

转载 作者:行者123 更新时间:2023-11-30 18:33:32 26 4
gpt4 key购买 nike

我将使用 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("");
}
}
}

关于c# - DataContractJsonSerializer 泛型列表包含元素类型的子类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17487576/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com