c# - 使用 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;
}
启动应用程序时,映射器运行并循环通过数据对象。不幸的是,单元格是空的。如何正确反序列化文件?
解决方案
- 在 LevelInfo 结构中,您有字段“单元格”,但在 Json -“地图”中。它们必须相同。
- JsonUtility 不能序列化/反序列化多维数组。
https://answers.unity.com/questions/1322769/parsing-nested-arrays-with-jsonutility.html https://docs.unity3d.com/Manual/script-Serialization.html
我相信您可以更改数据结构或使用其他序列化程序。
推荐阅读
- gradle - 如何在一个 gradle 项目中构建两个应用程序
- ruby-on-rails - 启用 public_file_server 时如何记录资产请求?
- html - 将图标移动到 h2 标题下方?
- elasticsearch - 使用 Kubernetes 的 Elasticsearch:使用 bootstrap.memory_lock 的内存锁不起作用
- php - 使用 Atom 进行 PHP 实时预览以编辑 WordPress 文件
- c - 自由链表
- python - 在特定条件下在 Dataframe 中添加新列
- python - 在for循环python中跳过错误的方法
- python - 无法使用生成的 tmux 窗口激活 conda 环境
- c - 将 SDL 与 C 结合使用 - 为什么窗口不显示?