Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing an empty array using Json.NET

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"} ]
}

If there is no message data to return, the JSON that I get back looks like this:

{
"messages": [ ]
}

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

When I try to deserialize the JSON, I'm using the following code:

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

The problem I'm running into is deserializing the JSON when the messages array is empty. When that occurs, I get the following exception:

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.

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!

like image 653
bmt22033 Avatar asked Jan 07 '23 17:01

bmt22033


1 Answers

You should either send just an array

[ {"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; } 
}

And then deserialize using it

var wrapper = JsonConvert.DeserializeObject<WrapperObject>(json, new JsonSerializerSettings
    {
        MissingMemberHandling = MissingMemberHandling.Ignore
    });
like image 79
Martin Vich Avatar answered Jan 17 '23 01:01

Martin Vich