首页 > 解决方案 > 使用 JsonUtility 反序列化嵌套对象

问题描述

我想反序列化包含关卡信息的 json 文件。给定这个名为1.json 的示例 .json 文件

{
  "name": "Level One",
  "map": [
    [{
      "groundTexture": "grass",
      "cellType": "empty",
      "masterField": null,
      "worldObjects": [{
        "worldObjectType": "player",
        "rotation": 90
      }]
    },{
      "groundTexture": "grass",
      "cellType": "obstacle",
      "masterField": null,
      "worldObjects": [{
        "worldObjectType": "tree",
        "rotation": 0
      }]
    }],[{
      "groundTexture": "grass",
      "cellType": "campFire",
      "masterField": null,
      "worldObjects": [{
        "worldObjectType": "campfire",
        "rotation": 270
      }]
    },{
      "groundTexture": "grass",
      "cellType": "related",
      "masterField": {
          "x": 1,
          "y": 0
      },
      "worldObjects": []
    }]
  ]
}

我想将该文件中的数据转换为一个类对象,该对象包含在运行时创建关卡所需的所有数据。我创建了一个只读取文件内容的阅读器

public class LevelReader : MonoBehaviour
{
    private string levelBasePath;

    private void Awake()
    {
        levelBasePath = $"{Application.dataPath}/ExternalFiles/Levels";
    }

    public string GetFileContent(string levelName)
    {
        string file = $"{levelName}.json";
        string filePath = Path.Combine(levelBasePath, file);
        return File.ReadAllText(filePath);
    }
}

以及将 json 字符串映射到LevelInfo对象的映射器。

public class LevelMapper : MonoBehaviour
{
    private void Start()
    {
        // DEBUGGING TEST

        LevelReader levelReader = GetComponent<LevelReader>();
        string levelContent = levelReader.GetFileContent("1");
        LevelInfo levelInfo = MapFileContentToLevelInfo(levelContent);

        Debug.Log(levelInfo.cells);
    }

    public LevelInfo MapFileContentToLevelInfo(string fileContent)
    {
        return JsonUtility.FromJson<LevelInfo>(fileContent);
    }
}

以下结构只是帮助创建一个包含所有关卡数据的对象:

[Serializable]
public struct LevelInfo
{
    public string name;
    public LevelCell[][] cells;
}

[Serializable]
public struct LevelCell
{
    public string groundTexture;
    public string cellType;
    public Vector2? masterField;
    public LevelWorldObject[] worldObjects;
}

[Serializable]
public struct LevelWorldObject
{
    public string worldObjectType;
    public int rotation;
}

启动应用程序时,映射器运行并循环通过数据对象。不幸的是,单元格是空的。如何正确反序列化文件?

标签: c#jsonunity3d

解决方案


  1. 在 LevelInfo 结构中,您有字段“单元格”,但在 Json -“地图”中。它们必须相同。
  2. JsonUtility 不能序列化/反序列化多维数组。

https://answers.unity.com/questions/1322769/parsing-nested-arrays-with-jsonutility.html https://docs.unity3d.com/Manual/script-Serialization.html

我相信您可以更改数据结构或使用其他序列化程序。


推荐阅读