2013-08-21 18 views
0

這是問題的後續這一個Serialize deserialize anonymous child JSON properties to model序列化反序列化匿名孩子JSON屬性模型中,當一些是空

我能夠正確地反序列化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":[]} 
數據3210

有什麼建議嗎?如果我可以有一個空字典,會很容易,但我不能那樣做嗎?

我的課是這樣的:

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

'JsonConvert.DeserializeObject (json);'適用於兩個樣本。 – I4V

+0

對不起我的錯誤......空字典的JSON是[]不是{} – Fuzzybear

回答

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; } 

您的幫助大家

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(); 
    } 
} 
+0

非常感謝這個答案,當我有機會時,我會嘗試一下我的代碼,如果作品我會標記爲選定的答案 – Fuzzybear