从字典的 JSON 数组访问键/值 C#,Unity [重复]

Posted

技术标签:

【中文标题】从字典的 JSON 数组访问键/值 C#,Unity [重复]【英文标题】:Accessing Key/Values from JSON Array of Dictionaries C#, Unity [duplicate] 【发布时间】:2021-09-16 14:45:40 【问题描述】:

给定如下 JSON 块,


  "word": "dog",
  "definitions": [
    
      "definition": "a smooth-textured sausage of minced beef or pork usually smoked; often served on a bread roll",
      "partOfSpeech": "noun"
    ,
    
      "definition": "go after with the intent to catch",
      "partOfSpeech": "verb"
    
  ]

我知道如何使用 Unity 内置的 JsonUtility 创建一个类来解析字符串...

WORDCLASS json = WORDCLASS.CreateFromJSON(someJSONstring);
  
            print(json.word);

JsonUtility 的示例类

[System.Serializable]
public class WORDCLASS

    public string word;

    public static WordJSON CreateFromJSON(string jsonString)
    
        return JsonUtility.FromJson<WordJSON>(jsonString);
    

我知道“定义”是一个字典数组(带有键“定义”和“partOfSpeech”......我只是不明白获取它们的正确方法......(即我想循环通过并打印出数组中的所有定义...

虽然我正在尝试使用内置的 Unity JsonUtility,但我对其他(更高效的)方法持开放态度,例如 Newton Json...

感谢您抽出宝贵时间提供帮助。

【问题讨论】:

我知道“定义”是一个字典数组——它看起来像是一个类数组,有两个属性public string definition get; set; public string partOfSpeech get; set; 。当键名是可变的但它们的值有一些固定的模式时使用字典。 虽然我似乎记得JsonUtility 只序列化公共字段而不是属性? How to auto-generate a C# class file from a JSON string 中的工具应该可以帮助您生成类以反序列化该 JSON。例如。转到json2csharp.com,粘贴您的 JSON,检查 [x] Use Fields 并推送 Convert,您将获得一组合理的类。 @dbc 感谢您提供指向 json2csharp.com 的链接...这让一切变得一清二楚!!! 它不是字典,而是一个简单的对象列表,每个对象有 2 个字符串字段:定义和 partOfSpeech。 【参考方案1】:

使用@DBC 提供的 json2csharp.com 链接快速解析了以下 JSON 的类定义...


  "word": "dog",
  "definitions": [
    
      "definition": "a smooth-textured sausage of minced beef or pork usually smoked; often served on a bread roll",
      "partOfSpeech": "noun"
    ,
    
      "definition": "go after with the intent to catch",
      "partOfSpeech": "verb"
    
  ]

到下面的类结构...

// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse); 
    //level 1
    public class Definition
    
        public string definition  get; set; 
        public string partOfSpeech  get; set; 
    
    //level 0
    public class Root
    
        public string word  get; set; 
        public List<Definition> definitions  get; set; 
    


本质上,您希望遍历的 Json 的每个级别都需要自己的类...

 Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJson);

            foreach (var v in myDeserializedClass.definitions)
            
                print("Here is a definition: " + v.definition);
            

【讨论】:

以上是关于从字典的 JSON 数组访问键/值 C#,Unity [重复]的主要内容,如果未能解决你的问题,请参考以下文章

如何检查json返回值是数组还是字典的形式

使用 jquery Json 返回值遍历 C# 字典

如何使用int数组作为字典键C# [重复]

如何在 Objective-C 中访问键的单个 JSON 值

如何使用 Swift 将具有两个不同键的两个值存储到数组或字典中? [关闭]

从字典数组中获取元素并将键保存为字符串,将值保存为字符串