Unable to deserialize JSON array to type foo

I am trying to parse data from oodle.com api feed using the JSON.NET lib. Part of the JSON response line for deserialization has the following "location" structure:

"location":{ "address":"123 foo Street", "zip":"94102", "citycode":"usa:ca:sanfrancisco:downtown", "name":"San Francisco (Downtown)", "state":"CA", "country":"USA", "latitude":"37.7878", "longitude":"-122.4101"}, 

however, I saw location instances declared as an empty array:

 "location":[], 

I am trying to deserialize it in a class like Location Data. This works fine when the location has valid data, but it does not work when the location is presented as an empty array. I tried adding attributes (NullValueHandling and Required) to set the location instance to null if the data is really an empty array, but I think that these attributes are only for serialization. If the array is empty, I get an exception

 Cannot deserialize JSON array into type 'LocationData' 

Is there any way to tell the deserializer not to complain and make the location object null if the deserialization array failed? Thanks!

 [JsonProperty(NullValueHandling = NullValueHandling.Ignore,Required=Required.AllowNull)] public LocationData location{get;set;} ... public class LocationData { public string zip { get; set; } public string address { get; set; } public string citycode { get; set; } public string name { get; set; } public string state { get; set; } public string country { get; set; } public decimal latitude { get; set; } public decimal longitude { get; set; } } 
+4
source share
1 answer

You can write your own converter for the LocationData type to turn marker tokens to zero.

Sort of:

 public class LocationDataConverter : JsonConverter { public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.StartArray) { reader.Read(); //move to end array return null; } var data = new LocationData(); serializer.Populate(reader, data); return data; } } 

Then just tag the LocationData class:

 [JsonConverter(typeof(LocationDataConverter))] public class LocationData {...} 
+2
source

All Articles