簡體   English   中英

使用JsonUtility反序列化嵌套對象

[英]Deserialize nested objects with JsonUtility

我想反序列化我的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;
}

啟動應用程序時,映射器將運行並循環遍歷數據對象。 不幸的是,細胞是空的。 如何正確反序列化文件?

  1. 在LevelInfo結構中,您有字段“cells”但在Json中 - “map”。 他們必須是一樣的。
  2. JsonUtility無法序列化/反序列化多維數組。

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

我相信您可以更改數據結構或使用其他序列化程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM