Deserializing an empty array using Json.NET

匿名 (未验证) 提交于 2019-12-03 02:33:02

问题:

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!

回答1:

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


回答2:

Create a wrapper class and deserialize the Json into it:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!