【问题标题】:Deserializing specific JSON fields into a list of objects in Unity将特定 JSON 字段反序列化为 Unity 中的对象列表
【发布时间】:2021-09-09 07:03:07
【问题描述】:

对于个人项目,我正在尝试将大型 Json 数组反序列化为对象列表,但是在遵循其他指南时我反复遇到问题。我有以下 json 文件:

{
  PokemonJSONList : [
    {
      "id": 1,
      "region": "Kanto",
      "name": "Bulbasaur",
      "typeList": [ "Grass", "Poison" ]
    },
    {
      "id": 2,
      "region": "Kanto",
      "name": "Ivysaur",
      "typeList": [ "Grass", "Poison" ]
    },
    {
      "id": 3,
      "region": "Kanto",
      "name": "Venusaur",
      "typeList": [ "Grass", "Poison" ]
    },
    {
      "id": 3,
      "form": "f2",
      "region": "Kalos",
      "name": "Mega Venusaur",
      "typeList": [ "Grass", "Poison" ]
    },
    {
      "id": 3,
      "form": "f3",
      "region": "Galar",
      "name": "G-Max Venusaur",
      "typeList": [ "Grass", "Poison" ]
    },
    {
      "id": 4,
      "region": "Kanto",
      "name": "Charmander",
      "typeList": [ "Fire" ]
    },
...
    {
      "id": 898,
      "form": "f4",
      "region": "Galar",
      "Legend": "true",
      "name": "Shadow Rider Calyrex",
      "typeList": [ "Psychic", "Grass" ]
    }
  ]
}

如您所见,一些 json 条目的键值对比其他条目多,因为这个 json 文件不仅仅用于这个项目。我只需要名称、区域、类型列表和图例(未显示,因为 json 文件的长度要长得多)字段。我也有这个课:

[System.Serializable]
public class PokemonList : MonoBehaviour
{
    public List<PokemonOBJ> PokemonJSONList;
}

打算接收这个json数据和这个类:

[System.Serializable]
public class PokemonOBJ : MonoBehaviour
{
    public string Name { get; set; }
    public string Region { get; set; }
    public List<string> TypeList { get; set; }
    public bool Legend { get; set; }
}

作为存储每个条目数据的基础对象。但是,当尝试像这样序列化 json 文件时:

string jsonString = @"Assets/JSON/data.json";
    public PokemonList PokemonDB;
PokemonDB = JsonUtility.FromJson<PokemonList>(jsonString);

导致“无法将 JSON 反序列化为 PokemonList 类型的新实例” 我使用的教程显示使用 PokemonOBJ for FromJson 但这会导致 vs 本身出现错误,我在这里有点迷失如何让它正常工作,以及我做错了什么。

【问题讨论】:

    标签: c# json unity3d json-deserialization


    【解决方案1】:

    来自docs

    仅支持普通的类和结构;派生自的类 UnityEngine.Object(例如 MonoBehaviour 或 ScriptableObject)是 不是。

    【讨论】:

    • 这修复了它!之前完全错过了这一点,这导致我犯了足够多的新错误,我认为我已经让它工作了。非常感谢!
    猜你喜欢
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-30
    • 2012-03-07
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多