简体   繁体   English

使用包含奇怪变量的数据使用JSON.NET反序列化JSON

[英]Deserialize JSON using JSON.NET with data containing weird variables

I am receiving some data in json (I do not have control over how the data is presented). 我在json中收到一些数据(我无法控制数据的呈现方式)。

Can this be deserialized using JsonConvert.DeserializeObject method from the JSON.NET library? 可以使用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}}"

I mean, I can't do something like: 我的意思是,我做不了类似的事情:

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

Also, this does not work: 此外,这不起作用:

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

Is there something obvious I am not getting here? 有什么明显的东西我没有到这里来吗? I managed to deserialize most of the json I had to deserialize but this one, I can't seem to figure it out. 我设法反序列化了我必须反序列化的大部分json,但是这个,我似乎无法弄明白。

Thanks a lot, and sorry if this is a dumb question! 非常感谢,如果这是一个愚蠢的问题,对不起!

You can deserialize this easily using Json.Net if you define your class correctly. 如果正确定义类,可以使用Json.Net轻松地反序列化。

Define your class like this: 像这样定义你的类:

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

Then, deserialize like this (where json is the JSON string from your question): 然后,像这样反序列化(其中json是你问题中的JSON字符串):

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

Then you can access the data from the Episodes dictionary in the Wrapper : 然后,您可以从WrapperEpisodes字典访问数据:

foreach (KeyValuePair<int, bool> kvp in wrapper.Episodes)
{
    Console.WriteLine(kvp.Key + " - " + kvp.Value);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM