C# 从没有模型的数组中获取 JSON 个键

C# Get JSON Keys from Array without Model

我有一个 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 dictonary = JS.Deserialize(JTR) as IEnumerable<KeyValuePair<string, JToken>>;

我的打印,输出是RandonName

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

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

JsonSerializer.Deserialize() 是一个静态方法。您不需要为 JsonSerializer.

创建实例

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

混淆

并反序列化为 Dictionary<string, List<Dictionary<string, string>>> 类型。

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

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

Sample .NET Fiddle

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

dictonary["RandonName"][0].Keys

获取列表中每一项的所有键:

using System.Linq;

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

如果您只需要第一个对象的 属性 个名称,那么您可以利用 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);
}
    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

one-liner的关键是将第一个JObject的children转换为JProperty