In this lesson, you will learn how to design C# class structures that map directly to complex, multi-level JSON files to ensure seamless data persistence.
When working with JsonUtility, a common pitfall is attempting to serialize a nested structure without explicitly defining the hierarchical relationship in your C# scripts. Unity’s JsonUtility requires that any class intended to be serialized as part of a JSON object must be marked with the [System.Serializable] attribute. If you have an array of objects or an object inside an object, you must mirror that "wrapper" pattern exactly in your code.
Structuring for Success
Imagine you are saving a player's inventory. Your JSON might look like this:
{
"playerName": "Hero",
"inventory": {
"gold": 500,
"items": [
{ "id": 1, "name": "Sword" },
{ "id": 2, "name": "Shield" }
]
}
}
To parse this, you cannot simply use a list. You must define a nested class structure that matches the depth of the JSON.
[System.Serializable]
public class ItemData {
public int id;
public string name;
}
[System.Serializable]
public class InventoryData {
public int gold;
public ItemData[] items; // Nested array
}
[System.Serializable]
public class PlayerSaveData {
public string playerName;
public InventoryData inventory; // Nested object
}
By nesting the classes (PlayerSaveData contains InventoryData, which contains ItemData), you create a data container that JsonUtility.FromJson<PlayerSaveData>(jsonString) can map perfectly.
If you try to skip a layer or fail to include the [System.Serializable] attribute on any class in the chain, Unity will ignore those fields during serialization, leading to data loss in your save files. Always ensure your C# object graph is as deep and structured as the JSON file itself.
Key Takeaway: To handle nested JSON structures, you must define matching nested C# classes, each marked with [System.Serializable], to provide a complete template for the serializer.