【问题标题】:Deserialize nested objects with JsonUtility使用 JsonUtility 反序列化嵌套对象
【发布时间】:2019-09-01 05:44:56
【问题描述】:

我想反序列化包含关卡信息的 json 文件。鉴于此示例 .json 文件名为 1.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# json unity3d


    【解决方案1】:
    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

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

    【讨论】:

      猜你喜欢
      • 2013-01-07
      • 1970-01-01
      • 1970-01-01
      • 2016-06-29
      • 1970-01-01
      • 2013-09-05
      • 2023-04-10
      • 2018-09-21
      • 2020-09-10
      相关资源
      最近更新 更多