这是这个问题的后续问题序列化反序列化匿名子JSON属性以建模
当我的数据如下时,我现在能够正确地反序列化JOSN,使用Location字段的字典对象
{"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":[]}
有什么建议吗?如果我可以有一本可以为null的字典,但我不能拥有它,那会很容易吗?
我的课程是这样的:
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反序列化程序进行反序列化,但都出现了相同的错误。
虽然你说过,你找到了答案,但可能其他SO用户想要使用它
通过创建自定义JsonConverter,反序列化可以为您的两个json 工作
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();
}
}
好的,这里给了我问题的解决方案如何使用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; }
非常感谢大家的帮助