您需要實現自定義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());
您發佈的內容無效JSON。使用[JSONLint](http://jsonlint.com/)來驗證您的JSON。 – rufer7
@ rufer7,小修復 – demo
'data'屬性怎麼樣,你需要忽略它嗎? –