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
MediumShare the team as a JSON code.
- In
CharacterBuild, makeStrengtha field,public int strength;, and markagility[SerializeField]. - Below it, write a
[System.Serializable]classTeamwithpublic List<CharacterBuild> heroes;. InTeamCode, make the listpublic Team team;and log its JSON. LoadCodereadscodeintoteamand logsLoaded 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
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular TurretRecap: Twin Cannon4Serialized Data
Serializable ClassesLists in the InspectorEnums in the InspectorRecap: Loot TableRecap: Roll the Loot2Interfaces in Unity
IDamageableInterfaces and TryGetComponentGetComponentsRecap: Interact KeyRecap: Nearest in ReachPractice on your own: Unity playground