[英]Deserialize JSON using JSON.NET with data containing weird variables
我在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,但是這個,我似乎無法弄明白。
非常感謝,如果這是一個愚蠢的問題,對不起!
如果正確定義類,可以使用Json.Net輕松地反序列化。
像這樣定義你的類:
class Wrapper
{
public Dictionary<int, bool> Episodes { get; set; }
}
然后,像這樣反序列化(其中json
是你問題中的JSON字符串):
Wrapper wrapper = JsonConvert.DeserializeObject<Wrapper>(json);
然后,您可以從Wrapper
的Episodes
字典訪問數據:
foreach (KeyValuePair<int, bool> kvp in wrapper.Episodes)
{
Console.WriteLine(kvp.Key + " - " + kvp.Value);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.