【问题标题】:Accessing Key/Values from JSON Array of Dictionaries C#, Unity [duplicate]从字典的 JSON 数组访问键/值 C#,Unity [重复]
【发布时间】: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。

标签: c# json unity3d json.net


【解决方案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);
            }

【讨论】:

    猜你喜欢
    • 2020-05-12
    • 2012-03-23
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 2018-04-16
    • 2018-05-29
    • 2019-01-27
    • 2021-12-05
    相关资源
    最近更新 更多