0
0
Unityframework~5 mins

JSON serialization in Unity

Choose your learning style9 modes available
Introduction

JSON serialization helps you turn your game data into text that can be saved or sent. It makes your data easy to store and share.

Saving player progress like scores or settings to a file.
Sending game data over the internet to a server or other players.
Loading game settings or levels from a saved file.
Debugging by printing data in a readable format.
Sharing configuration data between different parts of your game.
Syntax
Unity
using UnityEngine;

[System.Serializable]
public class PlayerData {
    public string playerName;
    public int score;
}

// To convert object to JSON string:
string jsonString = JsonUtility.ToJson(yourObject);

// To convert JSON string back to object:
PlayerData data = JsonUtility.FromJson<PlayerData>(jsonString);

The class you want to serialize must be marked with [System.Serializable].

Use JsonUtility.ToJson() to convert an object to JSON text.

Examples
This creates a player object and turns it into a JSON string.
Unity
PlayerData player = new PlayerData();
player.playerName = "Alex";
player.score = 100;
string json = JsonUtility.ToJson(player);
This takes a JSON string and turns it back into a PlayerData object.
Unity
string json = "{\"playerName\":\"Alex\",\"score\":100}";
PlayerData player = JsonUtility.FromJson<PlayerData>(json);
Sample Program

This Unity script creates a player object, converts it to JSON text, prints it, then reads the JSON back into an object and prints the data.

Unity
using UnityEngine;

[System.Serializable]
public class PlayerData {
    public string playerName;
    public int score;
}

public class JsonExample : MonoBehaviour {
    void Start() {
        PlayerData player = new PlayerData();
        player.playerName = "Alex";
        player.score = 100;

        // Serialize to JSON
        string json = JsonUtility.ToJson(player);
        Debug.Log("JSON string: " + json);

        // Deserialize back to object
        PlayerData loadedPlayer = JsonUtility.FromJson<PlayerData>(json);
        Debug.Log($"Player name: {loadedPlayer.playerName}, Score: {loadedPlayer.score}");
    }
}
OutputSuccess
Important Notes

Only public fields are serialized by default.

Properties (get/set) are not serialized by JsonUtility.

JsonUtility works well for simple data but not complex types like dictionaries.

Summary

JSON serialization converts objects to text and back.

Use JsonUtility.ToJson() and FromJson() in Unity.

Mark classes with [System.Serializable] and use public fields.