【问题标题】:C# Get JSON Keys from Array without ModelC# 从没有模型的数组中获取 JSON 键
【发布时间】:2022-06-19 02:24:37
【问题描述】:

我有一个 JSON 文件

{
    "RandonName": [
      {
        "RandomKey1": "Data",
        "RandomKey2": "Data",
        "RandomKey3": "Data",
        "RandomKey4": "Data",
        "RandomKey5": "Data"

      },
      {
        "RandomKey1": "Data",
        "RandomKey2": "Data",
        "RandomKey3": "Data",
        "RandomKey4": "Data",
        "RandomKey5": "Data"

      }
    ]
}

我的反序列化器

JsonTextReader JTR = new JsonTextReader(stringReader);
JsonSerializer JS = new JsonSerializer();

var dictionary = JS.Deserialize(JTR) as IEnumerable<KeyValuePair<string, JToken>>;

我的打印,输出是 RandonName

foreach(KeyValuePair<string, JToken> pair in sourceRoot)
{
    Console.WriteLine(pair.Key);               
}

我能以某种方式获取数组中的所有键名吗?

【问题讨论】:

  • RandonName 集合下的所有对象是否具有相同的属性?喜欢RandomKey1, ..., RandomKey5
  • 是的,他们有,只是让它更加抽象。

标签: c# json json.net


【解决方案1】:

JsonSerializer.Deserialize() 是一个静态方法。您无需为JsonSerializer 创建实例。

同时JToken 来自Newtonsoft.Json。我认为最好不要与System.Text.JsonNewtonsoft.Json 混淆。

并反序列化为Dictionary&lt;string, List&lt;Dictionary&lt;string, string&gt;&gt;&gt; 类型。

Dictionary<string, List<Dictionary<string, string>>> dictionary = JsonSerializer.Deserialize<Dictionary<string, List<Dictionary<string, string>>>>(JTR);

// Iterate for first item in RandonName dictionary
foreach (KeyValuePair<string, string> kvp in dictionary["RandonName"][0])
{
    Console.WriteLine(kvp.Key);
    Console.WriteLine(kvp.Value);
}
                
// Iterate for all items in RandonName dictionary
foreach (var items in dictionary["RandonName"])
{
    foreach (KeyValuePair<string, string> kvp in items)
    {
        Console.WriteLine(kvp.Key);
        Console.WriteLine(kvp.Value);
    }       
}

Sample .NET Fiddle

获取所有密钥(从第一项):

dictionary["RandonName"][0].Keys

从列表中的每个项目中获取所有键:

using System.Linq;

dictionary["RandonName"].SelectMany(x => x.Keys).ToList();

【讨论】:

  • 好的,这样可以,但是如果我需要继续使用 JToken 怎么办?
【解决方案2】:

如果您只需要第一个对象的属性名称,那么您可以利用Json.NET's Linq

var semiParsedJson = JObject.Parse(json);
var collection = (JArray)semiParsedJson["RandonName"];
var firstObject = (JObject)collection.First();
foreach (var property in firstObject.Properties())
{
    Console.WriteLine(property.Name);
}

【讨论】:

    【解决方案3】:
        string json = @"{
        'RandonName': [
    
          {
            'RandomKey1': 'Data',
            'RandomKey2': 'Data',
            'RandomKey3': 'Data',
            'RandomKey4': 'Data',
            'RandomKey5': 'Data'
    
    
          },
          {
            'RandomKey1': 'Data',
            'RandomKey2': 'Data',
            'RandomKey3': 'Data',
            'RandomKey4': 'Data',
            'RandomKey5': 'Data'
          }
        ]
    }
    ";
        Console.WriteLine(
          JObject.Parse(json)["RandonName"][0].Children<JProperty>().Select(x => x.Name));
    

    将打印出来:

    RandomKey1
    RandomKey2
    RandomKey3
    RandomKey4
    RandomKey5
    

    单线的关键是将第一个JObject的子代转换为JProperty

    【讨论】:

    • 好的,如果“RandomName”未知怎么办?
    • 根据您的代码,您可以获得有关“RandomName”正确名称的信息。然后在下一步中,您可以遍历找到的每个随机名称。
    • 代码假设RadonName可以被找到。我知道 OP 的问题是关于让RandonName 的孩子。这是答案中给出的代码的主要部分。
    猜你喜欢
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-29
    • 1970-01-01
    • 2015-08-22
    • 1970-01-01
    相关资源
    最近更新 更多