JSON serialization
- Game Development course
- Advanced
- Lesson 20/71
- 4 min
Learn to write objects to JSON with JsonUtility.
JSON Serialization and JsonUtility
Converting in-memory objects into plain text to save them to disk is called serialization. Unity provides the built-in JsonUtility class for this transformation.
[System.Serializable]
public class PlayerData {
public string playerName;
public int health;
}C# classes targeted for serialization must be decorated with the [System.Serializable] attribute.
The JsonUtility.ToJson Method
To turn a data object into a JSON string, JsonUtility.ToJson(data) is called. This method converts all public fields of the class into a structured key-value text payload.
PlayerData data = new PlayerData();
data.playerName = "Hero";
data.health = 100;
string json = JsonUtility.ToJson(data);The resulting string can be stored on disk, sent across networks, or inspected with ease.
Practice Generating a JSON string
Define a Start method. Inside, declare string jsonVeri = "Oyuncu: Savasci, Seviye: 5"; and print "JSON ozeti: " + jsonVeri to the console.
Starter code
using UnityEngine;
public class JsonTester : MonoBehaviour
{
// Start icinde jsonVeri degiskenini tanimla ve yazdir
}Sample solution
using UnityEngine;
public class JsonTester : MonoBehaviour
{
void Start()
{
string jsonVeri = "Oyuncu: Savasci, Seviye: 5";
Debug.Log("JSON ozeti: " + jsonVeri);
}
}Expected output
JSON ozeti: Oyuncu: Savasci, Seviye: 5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which attribute must precede a C# class for it to be serialized into JSON text by JsonUtility?
- [HideInInspector]
- [ExecuteInEditMode]
- [RequireComponent]
- [System.Serializable] Correct answer
Explanation: The [System.Serializable] attribute enables Unity to inspect class fields and convert them into JSON text.
2 Convert to JSON string
string json = JsonUtility.____(playerData);
string json = JsonUtility.ToJson(playerData);
Explanation: To convert an object into JSON format, 'JsonUtility.ToJson' is called.
3 JSON serialization elements
| Term | Meaning |
|---|---|
JsonUtility |
Built-in Unity JSON converter |
ToJson |
Converts object into JSON text |
[System.Serializable] |
Attribute enabling class serialization |
JSON |
Human- and machine-readable text format |