![](/img/trans.png)
[英]Deserialize Object returns null with nested JSON when trying to map it
[英]Trying to deserialize variable nested JSON
我從網站上獲得了下面的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的硬編碼類不是一個選項。
由於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; }
}
你嘗試過類似的東西:
Status datalist = JsonConvert.DeserializeObject<Status>(jsonstring);
你也需要讓你的工作者成為一個字典
public Dictionary<string, Worker> workers { get; set; }
這是使用Newtonsoft.Json
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.