使用具有随机根名称的C#反序列化JSON [英] Deserialize json with c# with random root names

查看:89
本文介绍了使用具有随机根名称的C#反序列化JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a json file which has random names in roots but same structure in child elements. I would like to get all the child elements in an array or a list.

示例json文件:

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

我已经尝试过这些课程,但不能做到.

I have tried these classes but could not do it.

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

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

所以我反序列化的预期输出就像List,其中包含json文件中的所有apiKeys.

So my expected output from deserialization is like List which contains all the apiKeys in json file.

谢谢.

推荐答案

在我看来,您的JSON直接表示Dictionary<string, ReportData>.没有包装对象,也没有列表.如果将JSON反序列化为该类型,那应该没问题.这是一个完整的示例:

It looks to me like your JSON represents a Dictionary<string, ReportData> directly. There's no wrapper object, and no lists involved. If you deserialize your JSON to that type, it should be fine. Here's a complete example:

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密钥列表,并且不关心与它们关联的字段名称,则可以使用:

If you just want the list of API keys, and you don't care about the field names associated with them, you can use:

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

这篇关于使用具有随机根名称的C#反序列化JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆