使用Json.NET反序列化一个空数组 [英] Deserializing an empty array using Json.NET
问题描述
我有一个使用Json.NET v7.0.1的C#应用程序.作为REST调用的结果,我以以下形式获取了一些JSON:
I've got a C# application that uses Json.NET v7.0.1. As a result of a REST call, I get back some JSON in the form of:
{
"messages": [ {"phoneNumber":"123-456-7890", "smsText":"abcd1234="},
{"phoneNumber":"234-567-8901", "smsText":"efgh5678="},
{"phoneNumber":"345-678-9012", "smsText":"12345asdf"} ]
}
如果没有要返回的消息数据,我返回的JSON如下所示:
If there is no message data to return, the JSON that I get back looks like this:
{
"messages": [ ]
}
我的Message类看起来像这样:
My Message class looks like this:
public class Message
{
public string PhoneNumber { get; set; }
public string SmsText { get; set; }
public Message()
{
}
public Message(string phoneNumber, string smsText)
{
PhoneNumber = phoneNumber;
SmsText = smsText;
}
}
当我尝试反序列化JSON时,我正在使用以下代码:
When I try to deserialize the JSON, I'm using the following code:
Message[] messages = JsonConvert.DeserializeObject<Message[]>(json, new JsonSerializerSettings
{
MissingMemberHandling = MissingMemberHandling.Ignore
});
我遇到的问题是在message数组为空时反序列化JSON.发生这种情况时,我得到以下异常:
The problem I'm running into is deserializing the JSON when the messages array is empty. When that occurs, I get the following exception:
无法反序列化当前JSON对象(例如{\"name \":\"value \"}) 变成类型"WindowsFormTestApplication.Message []",因为类型 需要JSON数组(例如[1,2,3])才能正确反序列化.\ r \ nTo 修复此错误,或者将JSON更改为JSON数组(例如[1,2,3]) 或更改反序列化类型,使其成为普通的.NET类型(例如 不是像整数这样的原始类型,不是像数组这样的集合类型 或列表),可以从JSON对象反序列化. 也可以将JsonObjectAttribute添加到类型中以强制将其 从JSON对象反序列化. 路径消息",第2行,位置15.
Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'WindowsFormTestApplication.Message[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'messages', line 2, position 15.
当JSON数组为空时,我希望我的Message []变量为null.我是否需要定制转换器来进行反序列化,还是我遗漏了一些明显的东西?谢谢!
When the JSON array is empty, I'd like my Message[] variable to be null. Do I need a custom converter to get this deserialized or am I missing something obvious? Thanks!
推荐答案
您应该只发送一个数组
[ {"phoneNumber":"123-456-7890", "smsText":"abcd1234="},
{"phoneNumber":"234-567-8901", "smsText":"efgh5678="},
{"phoneNumber":"345-678-9012", "smsText":"12345asdf"} ]
或者使用像这样的包装对象
Or use some wrapper object like this
public WrapperObject
{
public Message[] messages { get; set; }
}
然后使用它反序列化
var wrapper = JsonConvert.DeserializeObject<WrapperObject>(json, new JsonSerializerSettings
{
MissingMemberHandling = MissingMemberHandling.Ignore
});
这篇关于使用Json.NET反序列化一个空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!