这是对此问题的跟进问题Serialize deserialize anonymous child JSON properties to model
我可以使用位置字段的字典对象
在我的数据如下时正确地反序列化JOSN{"id":"2160336","activation_date":"2013-08-01","expiration_date":"2013-08-29","title":"Practice Manager","locations":{"103":"Cambridge","107":"London"}}
然而,当数组中没有值时,我会遇到问题,即有时会有像这样的数据
{"id":"2160336","activation_date":"2013-08-01","expiration_date":"2013-08-29","title":"Practice Manager","locations":[]}
有什么建议吗?如果我能拥有一本可以为空的字典,那会很容易,但是我不能拥有那么好吗?
我的课程看起来像这样:
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; }
}
我尝试使用JavaScriptSerializer和Newtonsoft JSON.net反序列化器进行反序列化,但都有相同的错误。
答案 0 :(得分:1)
虽然你说过,你找到了答案,也许其他一些SO用户想要使用它。
通过创建自定义JsonConverter ,反序列化可以适用于您的两个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();
}
}
答案 1 :(得分:0)
好的,这里给了我解决问题的方法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; }
非常感谢大家的帮助