Search code examples
c#jsonunity-game-enginedeserializationjson-deserialization

How to deserialize a list with JsonUtility


I'm trying to deserialize a list with JsonUtility.FromJson (a utility provided in Unity3D), unfortunately this data type cannot be deserialized because is not supported.

Below is attached as an example a simple class diagram where is showing the main class (Game) and the class variable (levels) of type List<Level>()

Example class diagram

Basically, I want to deserialize all the information with the next line code:

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

Solution

  • Not sure why it's not working for you, maybe you need to explain a little more and show some code, but here is a working example:

    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());
        }
    }
    

    Are you sure your json is valid? Are you getting any error messages?

    My best guess would be: Did you use automatic properties instead of fields in your data classes? Unity only serializes public fields or private ones with the [SerializeField] attribute, also see the docs about Unity Serialization.