将 JSON 对象反序列化到 .NET 列表中
JSON 是使用 Jersey 的 JAXB 序列化器在 Java 中创建的。 我需要在 .NET 应用程序中反序列化它。 问题出在序列化数组中: 如果数组包含多个项目,JSON 对象就像这样:
{"users":[{"name":"user1", "email":"[email protected]"},{"name":"user2", "email":"[email protected]"}]}
但是当对象仅包含一个项目时,它被序列化为一个简单对象,
{"users":{"name":"user1", "email":"[email protected]"}}
我想将其反序列化为 .NET 对象。
public class UserList{
public List<User> users {get;set;}
}
public class User{
public string name {get;set;}
public string email {get;set;}
}
标准 .NET 反序列化器不理解第二种情况。我尝试了 JSON.NET 默认反序列化器,但它抛出异常。也许需要正确配置?... 您能建议如何处理第一种和第二种情况吗? PS 我无法访问 Java 序列化器
JSON is created in Java using Jersey's JAXB serializer.
I need to deserialize it in .NET application.
The problem is in serialized arrays:
if array contains several items JSON object is like that:
{"users":[{"name":"user1", "email":"[email protected]"},{"name":"user2", "email":"[email protected]"}]}
but when object contains only one item it is serialized as a simple object
{"users":{"name":"user1", "email":"[email protected]"}}
I want to deserialize it into .NET object.
public class UserList{
public List<User> users {get;set;}
}
public class User{
public string name {get;set;}
public string email {get;set;}
}
Standard .NET deserializer does not understand the second case. I tried JSON.NET default deserializer but it throws exception. Maybe it needs to be configured properly?..
Can you suggest something how to deal with first and second cases.
P.S. I have no access to the Java serializer
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Json.Net 中,您可以创建一个可以像这样处理 JSON 的自定义转换器。
请查看反序列化 JSON,有时是数组,有时是对象,了解具体如何执行此操作。
In Json.Net, you can create a custom converter that can handle JSON like this.
Have a look at Deserializing JSON when sometimes array and sometimes object on how exactly to do that.
我一直在使用 Newtonsoft.JSON 来实现此目的,它确实可以很好地管理序列化集合。尝试一下。
I've been using Newtonsoft.JSON for this purpose and it did manage with serializing collections very good. Try it.