【问题标题】:Deserialize json with c# with random root names使用带有随机根名称的 c# 反序列化 json
【发布时间】:2019-05-10 14:23:36
【问题描述】:

我有一个 json 文件,它在根中具有随机名称,但在子元素中具有相同的结构。我想获取数组或列表中的所有子元素。

示例 json 文件:

{  
   "-LeHl495vL6vh-8CaLbD":{  
      "apiKey":"sr-tr-137-beea04e44cb452ba0da0ca090b7e61b4ec6ffc69"
   },
   "-LeHl6jrhUEMb7slZcpB":{  
      "apiKey":"sr-tr-137-aef7a23095c0c7baef1ef681bdd8bf9756ac2a17"
   }
}

我尝试过这些课程,但做不到。

public class RequestedReport
    {
        public Dictionary<string, List<ReportData>> ReportDatas { get; set; }
    }

    public class ReportData
    {
        public string apiKey { get; set; }
    }

所以我预期的反序列化输出类似于 List,其中包含 json 文件中的所有 apiKey。

提前致谢。

【问题讨论】:

  • 每个对象中有多个apiKey 条目还是只有一个?
  • 每个节点只有一个api key。
  • 乔恩有你的答案:)

标签: c# .net json json.net


【解决方案1】:

在我看来,您的 JSON 直接代表 Dictionary&lt;string, ReportData&gt;。没有包装对象,也没有涉及列表。如果您将 JSON 反序列化为该类型,则应该没问题。这是一个完整的例子:

using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;

class Program
{
    static void Main()
    {
        var json = File.ReadAllText("test.json");
        var reports = JsonConvert.DeserializeObject<Dictionary<string, ReportData>>(json);

        foreach (var pair in reports)
        {
            Console.WriteLine($"{pair.Key}: {pair.Value.ApiKey}");
        }
    }
}

public class ReportData
{
    [JsonProperty("apiKey")]
    public string ApiKey { get; set; }
}

如果您只需要 API 密钥列表,而不关心与它们关联的字段名称,则可以使用:

var apiKeys = reports.Values.Select(x => x.ApiKey).ToList();

【讨论】:

  • 如果随机值不能保证是唯一的,这是否有效?
  • 它只是拿钥匙没有什么特别的。所以我认为它会起作用
  • 我认为反序列化到字典中会因重复键而失败,而且我在您的原始问题中看不到任何东西可以保证该值的唯一性。它确实看起来很独特,但我已经学会了不信任数据。
  • @Broom 是的,这不适用于非唯一值。我相信 JSON.Net 会为每个键使用最后一个 apiKey。
  • @Broom:来自 RFC 7159:“当对象中的名称不唯一时,接收此类对象的软件的行为是不可预测的。”换句话说,任何产生这种 JSON 的东西实际上只是自找麻烦。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-21
  • 1970-01-01
  • 1970-01-01
  • 2012-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多