有人可以帮我反序列化C#中的以下 JSON 字符串:
{"legend_size": 1,
"data": {"series": ["2013-02-05", "2013-02-06", "2013-02-07", "2013-02-08", "2013-02-09", "2013-02-10", "2013-02-11", "2013-02-12", "2013-02-13", "2013-02-14"], "values":
{"CampaignHit": {"2013-02-14": 0, "2013-02-13": 0, "2013-02-12": 0, "2013-02-11": 0, "2013-02-10": 0, "2013-02-08": 11, "2013-02-05": 0, "2013-02-07": 14, "2013-02-06": 0, "2013-02-09": 0}}}}
我遇到CampaignHit
部分的问题。我无法对其进行反序列化。
以下是我创建的课程:
public class ExportedData
{
public string legend_size { get; set; }
public Data data { get; set; }
}
public class Data
{
public string[] series { get; set; }
public Values values { get; set; }
}
public class Values
{
public CampaignHit CampaignHit { get; set; }
}
public class CampaignHit
{
public CampaignData[] data { get; set; }
}
public class CampaignData
{
public object first { get; set; }
public object second { get; set; }
}
以下是反序列化json的代码:
var result = JsonConvert.DeserializeObject<ExportedData>(jsonResponse);
数据部分为空。如何更改CampaignHit
类,以便在反序列化后数据不为空。
答案 0 :(得分:1)
使用Newtonsoft.Json的解决方案:
JObject jObject = JObject.Parse(@"{
'legend_size': 1,
'data': {
'series': [
'2013-02-05', '2013-02-06', '2013-02-07', '2013-02-08', '2013-02-09', '2013-02-10', '2013-02-11', '2013-02-12', '2013-02-13', '2013-02-14'
],
'values': {
'CampaignHit': {
'2013-02-14': 0,
'2013-02-13': 0,
'2013-02-12': 0,
'2013-02-11': 0,
'2013-02-10': 0,
'2013-02-08': 11,
'2013-02-05': 0,
'2013-02-07': 14,
'2013-02-06': 0,
'2013-02-09': 0
}
}
}
}");
var campaignHit = jObject["data"]["values"]["CampaignHit"];
Dictionary<string,int> campaignHitDic = new Dictionary<string,int>();
foreach(JProperty c in campaignHit){
campaignHitDic.Add(c.Name,(int)c.Value);
}