如何使用 JsonUtility 反序列化列表

How to deserialize a list with JsonUtility

我正在尝试使用 JsonUtility.FromJson(Unity3D 中提供的实用程序)反序列化列表,不幸的是,这种数据类型无法反序列化,因为不受支持。

下面附有一个简单的 class 图表示例,其中显示了主要 class(游戏)和类型 List<Level>() 的 class 变量(关卡)

基本上,我想用下一行代码反序列化所有信息:

Game objResponse = JsonUtility.FromJson<Game> (www.text);

不确定为什么它对你不起作用,也许你需要多解释一点并展示一些代码,但这里有一个有效的例子:

using System.Collections.Generic;
using UnityEngine;

public class JsonExample : MonoBehaviour
{
    [System.Serializable] // May be required, but tested working without.
    public class Game
    {
        public int idCurrentLevel;
        public int idLastUnlockedLevel;
        public List<Level> levels;

        public Game()
        {
            idCurrentLevel = 17;
            idLastUnlockedLevel = 16;
            levels = new List<Level>()
            {
                new Level(){id = 0, name = "First World" },
                new Level(){id = 1, name = "Second World" },
            };
        }

        public override string ToString()
        {
            string str = "ID: " + idCurrentLevel + ", Levels: " + levels.Count;
            foreach (var level in levels)
                str += " Lvl: " + level.ToString();

            return str;
        }
    }

    [System.Serializable] // May be required, but tested working without.
    public class Level
    {
        public int id;
        public string name;

        public override string ToString()
        {
            return "Id: " + id + " Name: " + name;
        }
    }

    private void Start()
    {
        Game game = new Game();

        // Serialize
        string json = JsonUtility.ToJson(game);
        Debug.Log(json);

        // Deserialize
        Game loadedGame = JsonUtility.FromJson<Game>(json);
        Debug.Log("Loaded Game: " + loadedGame.ToString());
    }
}

您确定您的 json 有效吗?您是否收到任何错误消息?

我最好的猜测是:您是否在数据中使用了自动属性而不是字段 类? Unity 仅使用 [SerializeField] attribute, also see the docs about Unity Serialization.

序列化 public 字段或私有字段