【问题标题】:Deserialiazing Json dictionary to list [duplicate]反序列化Json字典以列出[重复]
【发布时间】:2018-09-08 20:21:30
【问题描述】:

我有一个 Json 文件,对象序列化正确,但问题是 json 有一个看起来像字典的东西,键是字符串“0”、“1”等等。

有什么方法可以在不涉及编写自己的解析器的情况下将它们正确反序列化为列表?

"WeaponSlots":{
        "0":{
           "WeaponInstalled":null,
           "AllowedWeaponTypes":{
              "0":{
                 "0":2
              }
           },
           "AllowedWeapons":null
        },
        "1":{
           "WeaponInstalled":null,
           "AllowedWeaponTypes":{
              "0":{
                 "0":2
              }
           },
           "AllowedWeapons":null
        }

示例文件:https://pastebin.com/i3LQ3L7j

【问题讨论】:

  • 试试JSON.NET
  • 这个 JSON 是什么创建的?你能修复它以使 WeaponSlots 成为正确的列表吗?
  • 您可以使用 app.quicktype.io/#l=cs 生成一组匹配的 C# 类,然后使用 Json.NET 将其解析为这些类型。

标签: c# .net json json.net


【解决方案1】:

您可以使用数据类型Dictionary<string, object> 来反序列化这个..

【讨论】:

    【解决方案2】:
    static void Main(string[] args)
    {
        // load the file.
        var file = File.ReadAllText("Example.json");
    
        // to generate the 'Example' classes from JSON I used
        // https://app.quicktype.io and changed the name to 'Example'
        var example = JsonConvert.DeserializeObject<Example>(file);
    
        // select the value of each dictionary entry into a list.
        var sections = example.Sections.Select(x => x.Value).ToList();
    }
    

    【讨论】:

      猜你喜欢
      • 2019-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      相关资源
      最近更新 更多