Menu
CoddyTech

JsonUtility

Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 30 of 64.

JSON is text that holds an object's values, so it can be logged, sent or written to a file. JsonUtility.ToJson(obj) turns an object into JSON and JsonUtility.FromJson<T>(json) makes a new T from it. JsonUtility follows the rules the Inspector follows, so it works on a [System.Serializable] class:

[System.Serializable]
public class PlayerProfile
{
    public string playerName = "Ana";
    public int level = 7;
    public List<string> badges = new List<string> { "Explorer", "Sharpshooter" };
    [SerializeField] private float hoursPlayed = 12.5f;
    private int secretCode = 1234;
    public int Rank { get; set; } = 3;
}
string json = JsonUtility.ToJson(new PlayerProfile());
// {"playerName":"Ana","level":7,"badges":["Explorer","Sharpshooter"],"hoursPlayed":12.5}
PlayerProfile copy = JsonUtility.FromJson<PlayerProfile>(json);

secretCode and Rank are missing. JsonUtility writes public fields and private fields marked [SerializeField], and nothing else: no properties, no static fields, no plain private fields. A Dictionary field is skipped too, and so is a field whose class is not [System.Serializable]. Those are the fields the Inspector leaves out as well. JsonUtility.ToJson(obj, true) writes the same JSON spread over several lines, easier to read.

A list inside a class is written, as badges is. A list on its own is not: JsonUtility needs an object at the top, so JsonUtility.ToJson(scores) for a List<int> of 10, 20 and 30 returns {}. Put the list in a class and convert that; a ScoreBoard holding the same list is written as {"scores":[10,20,30]}:

[System.Serializable]
public class ScoreBoard
{
    public List<int> scores;
}
challenge icon

Challenge

Medium

Share the team as a JSON code.

  1. In CharacterBuild, make Strength a field, public int strength;, and mark agility [SerializeField].
  2. Below it, write a [System.Serializable] class Team with public List<CharacterBuild> heroes;. In TeamCode, make the list public Team team; and log its JSON.
  3. LoadCode reads code into team and logs Loaded 3 heroes.

Press Play and press Space: the team shows as JSON. Then Check.

Try it yourself

using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class CharacterBuild
{
    public string hero;
    public int Strength { get; set; }
    private int agility;
}

All lessons in Game Architecture in Unity

Practice on your own: Unity playground