使用 Json.NET 反序列化一个空数组

Deserializing an empty array using Json.NET

我有一个使用 Json.NET v7.0.1 的 C# 应用程序。作为 REST 调用的结果,我以以下形式返回了一些 JSON:

{
"messages": [ {"phoneNumber":"123-456-7890", "smsText":"abcd1234="},
              {"phoneNumber":"234-567-8901", "smsText":"efgh5678="},
              {"phoneNumber":"345-678-9012", "smsText":"12345asdf"} ]
}

如果return没有消息数据,我返回的JSON是这样的:

{
"messages": [ ]
}

我的消息 class 看起来像这样:

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 时,我使用了以下代码:

Message[] messages = JsonConvert.DeserializeObject<Message[]>(json, new JsonSerializerSettings
{
    MissingMemberHandling = MissingMemberHandling.Ignore
});

我 运行 遇到的问题是在消息数组为空时反序列化 JSON。发生这种情况时,我得到以下异常:

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[] 变量为空。我是否需要自定义转换器来反序列化,或者我是否遗漏了一些明显的东西?谢谢!

您应该只发送一个数组

[ {"phoneNumber":"123-456-7890", "smsText":"abcd1234="},
              {"phoneNumber":"234-567-8901", "smsText":"efgh5678="},
              {"phoneNumber":"345-678-9012", "smsText":"12345asdf"} ]

或者像这样使用一些包装器对象

public WrapperObject 
{ 
    public Message[] messages { get; set; } 
}

然后使用它反序列化

var wrapper = JsonConvert.DeserializeObject<WrapperObject>(json, new JsonSerializerSettings
    {
        MissingMemberHandling = MissingMemberHandling.Ignore
    });

创建包装器 class 并将 Json 反序列化到其中:

public class MessageArray
{
    public Message[] Messages;
}

var messages = JsonConvert.DeserializeObject<MessageArray>(json, new JsonSerializerSettings
            {
                MissingMemberHandling = MissingMemberHandling.Ignore
            });