【问题标题】:Deserialize JSON using JSON.NET with data containing weird variables使用包含奇怪变量的数据的 JSON.NET 反序列化 JSON
【发布时间】:2013-12-04 01:34:44
【问题描述】:

我收到一些 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,但这一个,我似乎无法弄清楚。

非常感谢,如果这是一个愚蠢的问题,请见谅!

【问题讨论】:

    标签: c# json json.net json-deserialization


    【解决方案1】:

    如果你正确定义你的类,你可以使用 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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多