Question

This is a follow on question to this one Serialize deserialize anonymous child JSON properties to model

I am able to deserialize the JOSN correctly now when my data is as follows using dictionary objects for the Location field

{"id":"2160336","activation_date":"2013-08-01","expiration_date":"2013-08-29","title":"Practice Manager","locations":{"103":"Cambridge","107":"London"}}

Yet I run into problems when there is no values in the array, ie sometimes there is data like this

{"id":"2160336","activation_date":"2013-08-01","expiration_date":"2013-08-29","title":"Practice Manager","locations":[]}

Any suggestions? Would be easy if i could have a nullable dictionary but I can't have that right?

my classes look like this:

public class ItemResults
{
    public int Id { get; set; }

    public DateTime Activation_Date { get; set; }

    public DateTime Expiration_Date{ get; set; } 

    public string Title { get; set; }

    public Dictionary<string, string> Locations { get; set; }
}

and I have tried deserializing using JavaScriptSerializer and Newtonsoft JSON.net deserializer both with the same error.

Était-ce utile?

La solution 2

OK this here gave me the solution to the problem How to deserialize object that can be an array or a dictionary with Newtonsoft?

 public Dictionary<string, string> Location_Options
    {
        get
        {
            var json = this.LocationsJson.ToString();
            if (json == string.Empty | json == "[]")
            {
                return new Dictionary<string, string>();
            }
            else
            {
                return JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
            }
        }
    }

    [JsonProperty(PropertyName = "Locations")]
    public object LocationsJson { get; set; }

Many thanks for your help everyone

Autres conseils

Although you said, you found your answer, maybe some other SO users want to use this.

By creating a custom JsonConverter, Deserialization can work for both of your jsons

var res = JsonConvert.DeserializeObject<ItemResults>(json,new CustomConverter());

.

public class CustomConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Dictionary<string, string>);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (objectType == typeof(Dictionary<string, string>) && reader.TokenType== JsonToken.StartArray)
        {
            reader.Read(); // Read JsonToken.EndArray
            return new Dictionary<string,string>(); // or return null
        }
        serializer.Converters.Clear(); //To avoid Infinite recursion, remove this converter.
        return serializer.Deserialize<Dictionary<string,string>>(reader);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top