首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >试图反序列化变量嵌套的JSON

试图反序列化变量嵌套的JSON
EN

Stack Overflow用户
提问于 2014-02-19 19:58:38
回答 2查看 167关注 0票数 0

我从一个网站获得了下面的JSON代码;不幸的是,我无法控制或更改这个代码。员工部分是可变的,因此有可能添加或删除工人。(最少1名工人)

通常您会期望WORKERS部分是一个JSON数组,但不幸的是,它不是。

代码语言:javascript
复制
 {
"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字符串:

代码语言:javascript
复制
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;
}

不幸的是,这给了我一个错误:

代码语言:javascript
复制
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的硬编码类并不是一种选择。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-02-19 20:04:58

由于worker.n不是有效的属性名称,并且可以随工作人员的数量更改,所以请将员工声明为Dictionary<string, Worker>

代码语言:javascript
复制
var workers = JsonConvert.DeserializeObject<Status>(json);

代码语言:javascript
复制
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; }
}
票数 2
EN

Stack Overflow用户

发布于 2014-02-19 20:09:43

你有没有尝试过这样的方法:

代码语言:javascript
复制
Status datalist = JsonConvert.DeserializeObject<Status>(jsonstring);

你也需要让你的工人成为一本字典

代码语言:javascript
复制
public Dictionary<string, Worker> workers { get; set; }

这是使用Newtonsoft.Json

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21891062

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档