如何使用 JSON 对象的名称? (C#Newtonsoft.JSON)

How to get the name of a JSON object using? (C# Newtonsoft.JSON)

对于那些熟悉 Minecraft 的人来说,1.8 更新将声音存储为一个文件,并以加密哈希作为名称(您实际上只需将扩展名更改为 .ogg 即可播放)。资产文件夹中有一个存储为 JSON 文件的索引,它显示每个文件的正确声音名称以及加密的哈希名称。

我正在尝试创建一个程序,用户可以在该程序中键入名称,它会找到包含该名称的声音。索引以这种方式存储:

{ "objects":{"minecraft/sounds/mob/wither/idle2.ogg": {
  "hash": "6b2f86a35a3cd88320b55c029d77659915f83239",
  "size": 19332
},
"minecraft/lang/fil_PH.lang": {
  "hash": "e2c8f26c91005a795c08344d601b10c84936e89d",
  "size": 74035
},
"minecraft/sounds/note/snare.ogg": {
  "hash": "6967f0af60f480e81d32f1f8e5f88ccafec3a40c",
  "size": 3969
},
"minecraft/sounds/mob/villager/idle1.ogg": {
  "hash": "a772db3c8ac37dfeb3a761854fb96297257930ab",
  "size": 8605
},
"minecraft/sounds/mob/wither/hurt3.ogg": {
  "hash": "a4cf4ebe4c475cd6a4852d6b4228a4b64cf5cb00",
  "size": 16731
}

例如,如果用户键入 wither,它将获取 "minecraft/sounds/mob/wither/idle2.ogg" 的哈希值 和 "minecraft/sounds/mob/wither/hurt3.ogg"

我的问题是,如何获取对象名称(名称,而不是属性)以与用户的关键字字符串进行比较。

抱歉,如果我没有对某些词使用正确的术语,我不会对 JSON 文件进行太多修改。根据需要更正我的术语。

编辑

这个答案解决得更好(没有动态):

原回答:

这个有效:

var obj = JsonConvert.DeserializeObject<dynamic>(@"{ ""objects"":{""minecraft/sounds/mob/wither/idle2.ogg"": {
  ""hash"": ""6b2f86a35a3cd88320b55c029d77659915f83239"",
  ""size"": 19332
},
""minecraft/lang/fil_PH.lang"": {
  ""hash"": ""e2c8f26c91005a795c08344d601b10c84936e89d"",
  ""size"": 74035
},
""minecraft/sounds/note/snare.ogg"": {
  ""hash"": ""6967f0af60f480e81d32f1f8e5f88ccafec3a40c"",
  ""size"": 3969
},
""minecraft/sounds/mob/villager/idle1.ogg"": {
  ""hash"": ""a772db3c8ac37dfeb3a761854fb96297257930ab"",
  ""size"": 8605
},
""minecraft/sounds/mob/wither/hurt3.ogg"": {
  ""hash"": ""a4cf4ebe4c475cd6a4852d6b4228a4b64cf5cb00"",
  ""size"": 16731
}
}
}");

var t = obj.objects;
var names = new HashSet<String>();
foreach(JProperty fileThing in t)
{
    names.Add(fileThing.Name);
}
names.Dump();

给出:

minecraft/sounds/mob/wither/idle2.ogg
minecraft/lang/fil_PH.lang
minecraft/sounds/note/snare.ogg
minecraft/sounds/mob/villager/idle1.ogg
minecraft/sounds/mob/wither/hurt3.ogg

您也可以这样做:

var t = obj.objects;
var names = new Dictionary<String, String>();
foreach(JProperty fileThing in t)
{
    names.Add(fileThing.Name, (string)t[fileThing.Name].hash);
}

它为您提供了一个将原始名称链接到散列的字典:

minecraft/sounds/mob/wither/idle2.ogg -> 6b2f86a35a3cd88320b55c029d77659915f83239 minecraft/lang/fil_PH.lang -> e2c8f26c91005a795c08344d601b10c84936e89d minecraft/sounds/note/snare.ogg -> 6967f0af60f480e81d32f1f8e5f88ccafec3a40c minecraft/sounds/mob/villager/idle1.ogg -> a772db3c8ac37dfeb3a761854fb96297257930ab minecraft/sounds/mob/wither/hurt3.ogg -> a4cf4ebe4c475cd6a4852d6b4228a4b64cf5cb00

假设您有一个 jsonString 作为字符串变量。

jsonString = "";

JArray array = JArray.Parse(json);

foreach (JObject content in array.Children<JObject>())
{
    foreach (JProperty prop in content.Properties())
    {
        Console.WriteLine(prop.Name);
    }
}