如何使用JsonUtility反序列化列表

时间:2017-11-01 21:57:21

标签: c# json unity3d deserialization json-deserialization

我尝试使用JsonUtility.FromJson(Unity3D中提供的实用程序)反序列化列表,遗憾的是,由于不支持此数据类型,因此无法对其进行反序列化。

下面附有一个简单的类图,其中显示了类List<Level>()的主类(Game)和类变量(级别)

Example class diagram

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

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

1 个答案:

答案 0 :(得分:2)

不确定为什么它不适合你,也许你需要解释一下并展示一些代码,但这是一个有效的例子:

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]属性序列化公共字段或私有字段,另请参阅有关Unity Serialization的文档。