我从一个网站获得了下面的JSON代码;不幸的是,我无法控制或更改这个代码。员工部分是可变的,因此有可能添加或删除工人。(最少1名工人)
通常您会期望WORKERS部分是一个JSON数组,但不幸的是,它不是。
{
"confirmed_rewards": "0.00000",
"hashrate": 0,
"payout_history": "0.000000000",
"estimated_rewards": 0.0000000,
"workers": {
"worker.1": {
"alive": true,
"hashrate": 1
},
"worker.2": {
"alive": false,
"hashrate": 0
}
},
"efficiency": "100.00",
"shares": "0",
"rewardType": "4"}我尝试使用以下类反序列化JSON字符串:
public class Status
{
public string confirmed_rewards;
public int hashrate;
public string payout_history;
public string estimated_rewards;
public List<Worker> workers;
public string efficiency;
public string shares;
public string rewardType;
}
public class Worker
{
public WorkerStatus Status;
}
public class WorkerStatus
{
public bool alive;
public int hashrate;
}不幸的是,这给了我一个错误:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into
type 'System.Collections.Generic.List`1[Worker]' because the type requires a
JSON array (e.g. [1,2,3]) to deserialize correctly.我真的很好奇是否有一种反序列化的好方法。记住;号码(和名字!)工人们可以改变!因此,仅仅创建一个名为worker.1的硬编码类并不是一种选择。
发布于 2014-02-19 20:04:58
由于worker.n不是有效的属性名称,并且可以随工作人员的数量更改,所以请将员工声明为Dictionary<string, Worker>。
var workers = JsonConvert.DeserializeObject<Status>(json);public class Worker
{
public bool alive { get; set; }
public int hashrate { get; set; }
}
public class Status
{
public string confirmed_rewards { get; set; }
public int hashrate { get; set; }
public string payout_history { get; set; }
public double estimated_rewards { get; set; }
public Dictionary<string, Worker> workers { get; set; }
public string efficiency { get; set; }
public string shares { get; set; }
public string rewardType { get; set; }
}发布于 2014-02-19 20:09:43
你有没有尝试过这样的方法:
Status datalist = JsonConvert.DeserializeObject<Status>(jsonstring);你也需要让你的工人成为一本字典
public Dictionary<string, Worker> workers { get; set; }这是使用Newtonsoft.Json
https://stackoverflow.com/questions/21891062
复制相似问题