string json = @"{
'symbol':'XX',
'column_names":["Date","Open","High","Low","Close","Volume"],
'data':[
['2014-01-02',25.78,25.82,25.47,25.79,31843697.0],
['2013-12-31',25.81,26.04,25.77,25.96,22809682.0]]}";
public class DailyData
{
public string symbol { get; set; }
public List<OneDay> data { get; set; }
}
public class OneDay
{
public DateTime date { get; set; }
public double open { get; set; }
public double high { get; set; }
public double low { get; set; }
public double close { get; set; }
public double volume { get; set; }
}
DailyData dd = JsonConvert.DeserializeObject<DailyData>(json);
这是我的json字符串和类,我正在尝试使用Json.net
将其反序列化。如果我将公开List<OneDay> data { get; set; }
更改为public List<object> data { get; set; }
,则会有效。但在这种情况下,我还需要做更多的工作。是否有一个简洁的解决方案可以一次性反序列化它?
答案 0 :(得分:5)
是的,您必须使用JsonConverter
类告诉反序列化器如何将值数组映射到OneDay
类。
示例:强>
void Main()
{
string json = @"{
'symbol':'XX',
'column_names':['Date','Open','High','Low','Close','Volume'],
'data':[
['2014-01-02',25.78,25.82,25.47,25.79,31843697.0],
['2013-12-31',25.81,26.04,25.77,25.96,22809682.0]
]
}";
DailyData dd = JsonConvert.DeserializeObject<DailyData>(json);
dd.Dump();
}
class OneDayJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
OneDay obj = new OneDay();
obj.date = reader.ReadAsDateTime() ?? DateTime.MinValue;
obj.open = (double)(reader.ReadAsDecimal() ?? 0);
obj.high = (double)(reader.ReadAsDecimal()?? 0);
obj.low = (double)(reader.ReadAsDecimal() ?? 0);
obj.close = (double)(reader.ReadAsDecimal() ?? 0);
obj.volume = (double)(reader.ReadAsDecimal() ?? 0);
reader.Read();
return obj;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
public class DailyData
{
public string symbol { get; set; }
public List<OneDay> data { get; set; }
}
[JsonConverter(typeof(OneDayJsonConverter))]
public class OneDay
{
public DateTime date { get; set; }
public double open { get; set; }
public double high { get; set; }
public double low { get; set; }
public double close { get; set; }
public double volume { get; set; }
}
<强>结果:强>