2017-04-05 61 views
0
{ 
    "data" : { 
       "TTyTo3qHkFq8b-KsIHZOlQ" : { 
         "2016-05-01" : { 
          "value1" : 11, 
          "value2" : 87 
         }, 
         "2016-05-02" : { 
          "value1" : 2, 
          "value2" : 34 
         } 
       } 
    } 
} 

我有這個json。 我可以分析它變成下一個對象Dictionary<string, Dictionary<DateTime, Dictionary<string, int>>>解析json到帶有自定義類的字典中

如何從這個對象類似Dictionary<string, CustomClass1>做,其中

class CustomClass1 { 
    DateTime Date {get;set;} 
    Dictionary<string, int> Value {get;set;} 
} 

對於非實現我使用的是Json.NET。

+0

您發佈的內容無效JSON。使用[JSONLint](http://jsonlint.com/)來驗證您的JSON。 – rufer7

+0

@ rufer7,小修復 – demo

+0

'data'屬性怎麼樣,你需要忽略它嗎? –

回答

0

您需要實現自定義JsonConverter才能達到您想要的效果。

首先,你需要創建Root類,將代表整個JSON:

public class Root 
{ 
    public Dictionary<string, List<CustomClass1>> Data { get; set; } 
} 

public class CustomClass1 
{ 
    public DateTime Date { get; set; } 

    public Dictionary<string, int> Values { get; set; } 
} 

請注意這是Dictionary<string, List<CustomClass1>>,因爲你將不能夠反序列化到需要的類型Data的數據類型:Dictionary<string, CustomClass1>

之後,你需要實現自己的自定義JsonConverter

public class CustomClassConverter : JsonConverter 
{ 
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 
    { 
     //Implement if needed 
    } 

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) 
    { 
     var obj = (JObject)JObject.ReadFrom(reader); 

     var root = new Root(); 
     root.Data = new Dictionary<string, List<CustomClass1>>(); 

     JObject value = (JObject)obj.GetValue("data"); 
     foreach (JProperty prop1 in value.Properties()) 
     { 
      var customObjects = new List<CustomClass1>(); 
      foreach (JProperty prop2 in prop1.Values()) 
      { 
       var customObject = new CustomClass1(); 
       customObject.Date = DateTime.Parse(prop2.Name); 
       customObject.Values = new Dictionary<string, int>(); 
       foreach (JProperty prop3 in prop2.Values()) 
       { 
        customObject.Values.Add(prop3.Name, prop3.ToObject<int>()); 
       } 
       customObjects.Add(customObject); 
      } 
      root.Data.Add(prop1.Name, customObjects); 
     } 

     return root; 
    } 

    public override bool CanConvert(Type t) 
    { 
     return t.Equals(typeof(Root)); //Converter which handles only Root types 
    } 

    public override bool CanRead 
    { 
     get { return true; } 
    } 
} 

最後將它傳遞到DeserializeObject方法重載:

var root = JsonConvert.DeserializeObject<Root>(json, new CustomClassConverter());