3

我在 json 中接收到一些数据(我无法控制数据的呈现方式)。

这可以使用 JSON.NET 库中的 JsonConvert.DeserializeObject 方法反序列化吗?

"{'episodes':{'1':true,'2':true,'3':true,'4':true,'5':true,'6':true,'7':true,'8':true,'9':true,'10':true,'11':true,'12':true,'13':true,'14':true,'15':true,'16':true,'17':true,'18':true,'19':true,'20':true,'21':true,'22':true,'23':true,'24':true}}"

我的意思是,我不能做这样的事情:

public class Episodes {
public bool 1;
public bool 2;
public bool 3;
...
}

此外,这不起作用:

public class Episode
{
     [JsonProperty("1")]
    public bool One { get; set; }
     [JsonProperty("2")]
     public bool Two { get; set; }
     [JsonProperty("3")]
     public bool Three { get; set; }
     [JsonProperty("4")]
     public bool Four { get; set; }
     [JsonProperty("5")]
     public bool Five { get; set; }
     [JsonProperty("6")]
     public bool Six { get; set; }
     [JsonProperty("7")]
     public bool Seven { get; set; }
     [JsonProperty("8")]
     public bool Eight { get; set; }
     [JsonProperty("9")]
     public bool Nine { get; set; }
     [JsonProperty("10")]
     public bool Ten { get; set; }
     [JsonProperty("11")]
     public bool Eleven { get; set; }
     [JsonProperty("12")]
     public bool Twelve { get; set; }
     [JsonProperty("13")]
     public bool Thirteen { get; set; }
     ...
}
var result = JsonConvert.DeserializeObject<Episode>(json); // Every property is False

有什么明显的我没有到达这里吗?我设法反序列化了我必须反序列化的大部分 json,但是这个,我似乎无法弄清楚。

非常感谢,如果这是一个愚蠢的问题,对不起!

4

1 回答 1

2

如果你正确定义了你的类,你可以使用 Json.Net 轻松地反序列化它。

像这样定义你的类:

class Wrapper
{
    public Dictionary<int, bool> Episodes { get; set; }
}

然后,像这样反序列化(json您问题的 JSON 字符串在哪里):

Wrapper wrapper = JsonConvert.DeserializeObject<Wrapper>(json);

然后您可以从以下Episodes字典中访问数据Wrapper

foreach (KeyValuePair<int, bool> kvp in wrapper.Episodes)
{
    Console.WriteLine(kvp.Key + " - " + kvp.Value);
}
于 2013-12-04T05:02:26.060 回答