Bird
Raised Fist0
Unityframework~10 mins

JSON serialization in Unity - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - JSON serialization
Create Object
↓
Convert Object to JSON String
↓
Use JSON String (Save/Send)
↓
Convert JSON String back to Object
↓
Use Object in Program
This flow shows how an object is turned into a JSON string and back, so it can be saved or sent and then used again.
Execution Sample
Unity
using UnityEngine;

[System.Serializable]
public class Player {
  public string name;
  public int score;
}

public class Example : MonoBehaviour {
  void Start() {
    Player p = new Player { name = "Anna", score = 10 };
    string json = JsonUtility.ToJson(p);
    Debug.Log(json);
  }
}
This code creates a Player object, converts it to a JSON string, and prints the JSON string.
Execution Table
StepActionObject StateJSON StringOutput
1Create Player objectname="Anna", score=10
2Serialize object to JSONname="Anna", score=10{"name":"Anna","score":10}
3Print JSON stringname="Anna", score=10{"name":"Anna","score":10}{"name":"Anna","score":10}
4Deserialize JSON back to objectempty Player object{"name":"Anna","score":10}name="Anna", score=10
5Use deserialized objectname="Anna", score=10Player name: Anna, score: 10
💡 Serialization and deserialization complete, object restored from JSON string.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 4Final
p (Player object)nullname="Anna", score=10name="Anna", score=10name="Anna", score=10name="Anna", score=10
json (string)""""{"name":"Anna","score":10}{"name":"Anna","score":10}{"name":"Anna","score":10}
Key Moments - 3 Insights
Why do we need the [System.Serializable] attribute on the Player class?
Unity requires [System.Serializable] to know that the Player class can be converted to JSON. Without it, JsonUtility.ToJson will not work (see Step 2 in execution_table).
Does the JSON string contain the exact same data as the object?
Yes, the JSON string is a text version of the object's data (Step 2 and Step 3). It does not include methods or behavior, only data fields.
What happens if we change the JSON string before deserializing?
If the JSON string is changed to valid JSON with matching fields, the deserialized object will reflect those changes (Step 4). Invalid JSON causes errors.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'json' after Step 2?
A{"name":"Anna","score":10}
Bname="Anna", score=10
Cnull
D""
💡 Hint
Check the 'JSON String' column in row for Step 2 in execution_table.
At which step is the Player object first created with data?
AStep 4
BStep 1
CStep 3
DStep 5
💡 Hint
Look at the 'Action' and 'Object State' columns in execution_table for Step 1.
If we remove [System.Serializable] from Player class, what happens at Step 2?
AJsonUtility.ToJson returns the full object data
BThe program crashes immediately
CJsonUtility.ToJson returns an empty JSON string
DThe JSON string contains method names
💡 Hint
Refer to key_moments about the importance of [System.Serializable] and Step 2 in execution_table.
Concept Snapshot
JSON serialization in Unity:
- Mark classes with [System.Serializable]
- Use JsonUtility.ToJson(object) to convert to JSON string
- Use JsonUtility.FromJson<T>(json) to convert back
- JSON stores data only, no methods
- Useful for saving or sending data
Full Transcript
In Unity, JSON serialization means turning an object into a JSON string and back. First, you create an object with data. Then, you use JsonUtility.ToJson to convert it into a JSON string, which is text that represents the object's data. This string can be saved or sent somewhere. Later, you can convert the JSON string back into an object with JsonUtility.FromJson. The class must have the [System.Serializable] attribute so Unity knows it can be serialized. The JSON string only contains data fields, not methods or behavior. This process helps store or share data easily.

Practice

(1/5)
1.

What is the main purpose of JSON serialization in Unity?

easy
A. Create 3D models from code
B. Convert objects into text format and back
C. Compile scripts faster
D. Optimize game performance automatically

Solution

  1. Step 1: Understand JSON serialization

    JSON serialization means turning objects into text so they can be saved or sent.
  2. Step 2: Recognize Unity's use

    Unity uses JSON serialization to save object data as text and load it back.
  3. Final Answer:

    Convert objects into text format and back -> Option B
  4. Quick Check:

    JSON serialization = Convert objects to text and back [OK]
Hint: Think: saving objects as readable text [OK]
Common Mistakes:
  • Confusing serialization with 3D modeling
  • Thinking it speeds up script compilation
  • Assuming it optimizes performance automatically
2.

Which of the following is the correct way to serialize an object player to JSON in Unity?

Player player = new Player();
easy
A. string json = JsonUtility.ToJson(player);
B. string json = Json.Serialize(player);
C. string json = JsonUtility.FromJson(player);
D. string json = player.ToJson();

Solution

  1. Step 1: Identify Unity's serialization method

    Unity uses JsonUtility.ToJson() to convert objects to JSON text.
  2. Step 2: Check method usage

    JsonUtility.ToJson(player) correctly serializes the player object.
  3. Final Answer:

    string json = JsonUtility.ToJson(player); -> Option A
  4. Quick Check:

    Serialize with JsonUtility.ToJson() [OK]
Hint: Use JsonUtility.ToJson() to serialize objects [OK]
Common Mistakes:
  • Using FromJson() instead of ToJson()
  • Calling non-existent Json.Serialize() method
  • Trying to call ToJson() on the object itself
3.

Given the following code, what will be the output?

[System.Serializable]
public class Player {
    public string name = "Alex";
    public int score = 10;
}

Player player = new Player();
string json = JsonUtility.ToJson(player);
Debug.Log(json);
medium
A. {"name":"Alex","score":10}
B. {"name":"Alex"}
C. {"score":10}
D. Error: Player class not serializable

Solution

  1. Step 1: Check class serialization

    The Player class is marked [System.Serializable], so it can be converted to JSON.
  2. Step 2: Understand JsonUtility.ToJson output

    It converts all public fields to JSON key-value pairs, so name and score appear.
  3. Final Answer:

    {"name":"Alex","score":10} -> Option A
  4. Quick Check:

    Serializable class fields appear in JSON [OK]
Hint: Serializable class fields become JSON keys [OK]
Common Mistakes:
  • Forgetting [System.Serializable] attribute
  • Expecting private fields to appear
  • Thinking only one field is serialized
4.

What is wrong with this code snippet for deserializing JSON into a Player object?

string json = "{\"name\":\"Sam\", \"score\":15}";
Player player = JsonUtility.ToJson(json);
medium
A. JSON string is not properly formatted
B. Player class must be private
C. Using ToJson() instead of FromJson() for deserialization
D. Missing semicolon after JSON string

Solution

  1. Step 1: Identify method misuse

    JsonUtility.ToJson() is for serialization, not deserialization.
  2. Step 2: Correct method for deserialization

    Use JsonUtility.FromJson<Player>(json) to convert JSON text back to Player object.
  3. Final Answer:

    Using ToJson() instead of FromJson() for deserialization -> Option C
  4. Quick Check:

    Deserialize with FromJson(), not ToJson() [OK]
Hint: Use FromJson() to convert JSON text to object [OK]
Common Mistakes:
  • Mixing ToJson() and FromJson() methods
  • Assuming JSON string format is wrong
  • Thinking class visibility affects serialization
5.

You want to save a list of Player objects to JSON and load them back later. Which approach correctly handles this in Unity?

hard
A. Serialize the list directly with JsonUtility.ToJson(playersList)
B. Use JsonUtility.FromJson<List<Player>>(json) to deserialize
C. Serialize each Player separately and concatenate JSON strings
D. Wrap the list in a serializable container class and serialize that

Solution

  1. Step 1: Understand Unity's JsonUtility limitation

    JsonUtility cannot serialize lists directly; it needs a wrapper class.
  2. Step 2: Use a container class

    Create a [System.Serializable] class with a public List<Player> field and serialize that.
  3. Final Answer:

    Wrap the list in a serializable container class and serialize that -> Option D
  4. Quick Check:

    Wrap lists in container class for JSON serialization [OK]
Hint: Wrap lists in a class before serializing [OK]
Common Mistakes:
  • Trying to serialize lists directly
  • Concatenating JSON strings manually
  • Using FromJson with generic List type
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard