5

I am trying to parse out data from oodle.com api feed using the JSON.NET lib. Part of the response JSON string to deserialize 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've seen instances of location declared as an empty array:

"location":[],

I am trying to deserialize it in a class of type Location Data. This works perfect when location has valid data in it but it does not work well when the location is represented as an empty array. I tried adding the attributes (NullValueHandling & Required) to have set the location instance as null if the data is indeed an empty array but I think these attribs are meant for serialization only. If the array is empty I get an exception

Cannot deserialize JSON array into type 'LocationData'

Is there a way to tell the deserializer to not complain and make the location object null if the array the deserialization fails? 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; }
     }
3
  • 1
    There are no arrays in your first example, but there's an empty one in your second... does JSON.NET care what the "location" data is (single object or array of objects)? Commented Sep 11, 2010 at 17:23
  • Good point. I just noticed that. I will contact the data provider (oodle.com dev api) to try to get an explanation. It seems like the data type in this case is different to weather is has data or null. Is there a data structure that can contain both? Is there a trick to JSON.NET that tells it to serialize it to LocationData if it has data otherwise just put NULL if it's an empty array? Commented Sep 12, 2010 at 14:59
  • 1
    Problem turn out to be JSON construction from PHP. location object was defined as a hash $somehash = array(); and it is populated as: if ($foo) { $location{'foo'} = $foo; } in php json_encode converts $somehash to somehash[] even though $somehash is intended to be used as a hashed object instead of an array... So the solution is not to instantiate the variable $somehash = array(); until you have the first item to populate. That will serialize the json object as a NULL instead of an array. Commented Sep 14, 2010 at 18:28

1 Answer 1

2

You can write a custom converter for the LocationData type to turn array tokens in to null.

Something like:

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 {...}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.