0
0
Unityframework~15 mins

JSON serialization in Unity - Deep Dive

Choose your learning style9 modes available
Overview - JSON serialization
What is it?
JSON serialization is the process of converting data objects in Unity into a JSON string format and back. This allows data to be saved, sent, or loaded in a text format that is easy to read and share. Unity provides built-in tools to serialize objects to JSON and deserialize JSON back into objects. This helps in saving game states, settings, or communicating with web services.
Why it matters
Without JSON serialization, sharing or saving complex data in Unity would be difficult and error-prone. Developers would have to write custom code to convert data into formats that other systems understand. JSON serialization makes data exchange simple and standardized, enabling features like saving player progress, loading configurations, or interacting with online APIs. Without it, games would lack flexibility and interoperability.
Where it fits
Before learning JSON serialization, you should understand basic C# classes and data structures in Unity. After mastering serialization, you can explore networking, saving/loading systems, and working with REST APIs. It fits into the data management and communication part of game development.
Mental Model
Core Idea
JSON serialization is like translating Unity objects into a universal text language so they can be saved, shared, or restored exactly as they were.
Think of it like...
Imagine packing your belongings into labeled boxes before moving house. JSON serialization packs your data into a neat, labeled text box that can be unpacked anywhere later.
Unity Object
   │
   ▼
[JSON Serializer]
   │
   ▼
"{ \"name\": \"Player1\", \"score\": 100 }"
   │
   ▼
[JSON Deserializer]
   │
   ▼
Unity Object (restored)
Build-Up - 7 Steps
1
FoundationUnderstanding JSON Format Basics
🤔
Concept: Learn what JSON is and how it represents data as text.
JSON (JavaScript Object Notation) is a simple text format that uses key-value pairs and arrays to represent data. For example, a player object might look like {"name": "Alice", "score": 50}. JSON is easy to read and write for humans and machines.
Result
You can recognize JSON strings and understand their structure.
Understanding JSON format is essential because serialization converts objects into this exact text structure.
2
FoundationUnity Classes and Data Structures
🤔
Concept: Know how Unity uses classes and fields to hold data.
In Unity, data is stored in classes with fields like strings, numbers, or lists. For example, a Player class might have a name and score field. These fields hold the data you want to save or send.
Result
You can create simple classes that represent game data.
Knowing how data is structured in Unity helps you understand what needs to be serialized.
3
IntermediateUsing JsonUtility for Serialization
🤔Before reading on: do you think JsonUtility can serialize any Unity object or only specific types? Commit to your answer.
Concept: Learn how to convert Unity objects to JSON strings using JsonUtility.
Unity provides JsonUtility.ToJson(object) to convert an object into a JSON string. For example, calling ToJson on a Player instance creates a JSON string representing its fields. This method works with classes that have public fields or non-public fields marked with [SerializeField].
Result
You can turn Unity objects into JSON text easily.
Knowing JsonUtility's limitations helps avoid bugs when serializing complex or unsupported types.
4
IntermediateDeserializing JSON Back to Objects
🤔Before reading on: do you think deserialization creates a new object or modifies an existing one? Commit to your answer.
Concept: Learn how to restore Unity objects from JSON strings.
Use JsonUtility.FromJson(jsonString) to create a new object of type T from JSON text. This recreates the data fields as they were when serialized. You can also use FromJsonOverwrite to update an existing object with JSON data.
Result
You can restore saved data or received JSON into usable Unity objects.
Understanding deserialization is key to loading saved states or processing data from external sources.
5
IntermediateHandling Nested and Complex Data
🤔Before reading on: do you think JsonUtility supports serializing lists and nested classes automatically? Commit to your answer.
Concept: Learn how JsonUtility deals with nested objects and collections.
JsonUtility can serialize nested classes and arrays/lists if their fields are public or marked with [SerializeField]. For example, a Player class with a List of InventoryItems can be serialized fully. However, it does not support dictionaries or polymorphism well.
Result
You can serialize more complex data structures but must know JsonUtility's limits.
Knowing what JsonUtility supports helps design data structures that serialize correctly.
6
AdvancedCustom Serialization with Interfaces
🤔Before reading on: can you customize how JsonUtility serializes a field by default? Commit to your answer.
Concept: Explore ways to customize serialization beyond JsonUtility's default behavior.
JsonUtility does not support custom converters or attributes like Newtonsoft.Json. To customize, you can implement your own serialization methods or use alternative libraries like Newtonsoft.Json for Unity. This allows handling dictionaries, polymorphism, or ignoring fields.
Result
You can handle complex serialization needs by extending or replacing JsonUtility.
Understanding JsonUtility's limits motivates using or building custom serializers for advanced scenarios.
7
ExpertPerformance and Memory Considerations
🤔Before reading on: do you think JSON serialization is always fast and memory-efficient? Commit to your answer.
Concept: Learn about the runtime cost and memory impact of JSON serialization in Unity.
JSON serialization involves string creation and parsing, which can be slow or cause garbage collection spikes if done frequently. JsonUtility is faster than some alternatives but still costly for large data or frequent calls. Profiling and batching serialization can improve performance.
Result
You can write efficient serialization code that avoids frame drops or memory issues.
Knowing serialization costs helps optimize game performance and avoid subtle bugs.
Under the Hood
JsonUtility uses Unity's internal serialization system to convert public fields and fields marked with [SerializeField] into JSON text. It reflects on the object's fields at runtime, reads their values, and writes them as JSON key-value pairs. During deserialization, it parses the JSON string and assigns values back to the object's fields. It does not serialize private fields without [SerializeField] or properties and lacks support for complex types like dictionaries or polymorphic classes.
Why designed this way?
Unity designed JsonUtility to be lightweight and fast, focusing on common use cases like saving simple data and communicating with web APIs. It avoids complex features to keep performance high and integration seamless with Unity's serialization system. Alternatives like Newtonsoft.Json offer more features but at a higher cost and complexity, so Unity chose a simpler approach for most game needs.
┌───────────────┐        ┌───────────────┐        ┌───────────────┐
│ Unity Object  │ ──────▶│ JsonUtility   │ ──────▶│ JSON String   │
│ (public data) │        │ (serializer)  │        │ (text format) │
└───────────────┘        └───────────────┘        └───────────────┘
       ▲                                               │
       │                                               ▼
┌───────────────┐        ┌───────────────┐        ┌───────────────┐
│ JSON String   │ ──────▶│ JsonUtility   │ ──────▶│ Unity Object  │
│ (text format) │        │ (deserializer)│        │ (restored)    │
└───────────────┘        └───────────────┘        └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does JsonUtility serialize private fields by default? Commit to yes or no.
Common Belief:JsonUtility serializes all fields of an object, including private ones.
Tap to reveal reality
Reality:JsonUtility only serializes public fields and fields marked with [SerializeField]. Private fields without this attribute are ignored.
Why it matters:Assuming private fields serialize causes missing data when saving or loading, leading to bugs and lost game state.
Quick: Can JsonUtility serialize dictionaries directly? Commit to yes or no.
Common Belief:JsonUtility can serialize any C# data structure, including dictionaries.
Tap to reveal reality
Reality:JsonUtility does not support dictionaries or other complex types like polymorphic classes.
Why it matters:Trying to serialize unsupported types causes runtime errors or incomplete data, frustrating debugging.
Quick: Does deserialization modify the original object or create a new one by default? Commit to your answer.
Common Belief:Deserialization always updates the existing object with new data.
Tap to reveal reality
Reality:JsonUtility.FromJson creates a new object instance; to update an existing object, you must use FromJsonOverwrite explicitly.
Why it matters:Misunderstanding this leads to unexpected behavior where changes are not applied to the intended object.
Quick: Is JSON serialization always fast and memory-efficient? Commit to yes or no.
Common Belief:JSON serialization is lightweight and has negligible performance impact.
Tap to reveal reality
Reality:Serialization creates strings and allocates memory, which can cause slowdowns and garbage collection if overused.
Why it matters:Ignoring performance costs can cause frame drops or memory spikes in games, harming user experience.
Expert Zone
1
JsonUtility ignores properties and only serializes fields, which can surprise developers expecting full object serialization.
2
The order of fields in JSON output is not guaranteed, so relying on field order for parsing is unsafe.
3
JsonUtility does not support polymorphism; derived class fields are lost unless handled manually.
When NOT to use
Avoid JsonUtility when you need to serialize dictionaries, polymorphic types, or require custom converters. Instead, use libraries like Newtonsoft.Json or System.Text.Json with Unity wrappers for advanced scenarios.
Production Patterns
In production, JsonUtility is often used for quick save/load of simple data, configuration files, or sending data to web APIs. For complex data, teams combine it with custom serialization or third-party libraries. Profiling serialization performance and minimizing frequency is common to maintain smooth gameplay.
Connections
REST APIs
JSON serialization enables communication with REST APIs by converting Unity objects to JSON requests and parsing JSON responses.
Understanding JSON serialization helps integrate Unity games with web services, enabling features like leaderboards or cloud saves.
Data Persistence
Serialization is a core technique for saving and loading game data persistently on disk or cloud.
Mastering JSON serialization is essential for building reliable save systems that restore player progress accurately.
Language Translation
Both JSON serialization and language translation involve converting information from one form to another while preserving meaning.
Seeing serialization as translation clarifies why data must be structured carefully to avoid loss or corruption.
Common Pitfalls
#1Trying to serialize private fields without [SerializeField] attribute.
Wrong approach:public class Player { private int score = 10; } string json = JsonUtility.ToJson(player);
Correct approach:public class Player { [SerializeField] private int score = 10; } string json = JsonUtility.ToJson(player);
Root cause:Misunderstanding that JsonUtility only serializes public fields or those explicitly marked.
#2Attempting to serialize a Dictionary directly with JsonUtility.
Wrong approach:public class Inventory { public Dictionary items; } string json = JsonUtility.ToJson(inventory);
Correct approach:Use a List of key-value pairs or a custom serializable class instead of Dictionary for JsonUtility.
Root cause:JsonUtility does not support dictionaries, causing serialization to fail silently or produce empty data.
#3Using FromJson expecting it to update an existing object instance.
Wrong approach:JsonUtility.FromJson(jsonString); // expecting existing player to update
Correct approach:JsonUtility.FromJsonOverwrite(jsonString, existingPlayer); // updates existing object
Root cause:Confusing FromJson (creates new object) with FromJsonOverwrite (modifies existing object).
Key Takeaways
JSON serialization converts Unity objects into a text format that can be saved, shared, or restored.
Unity's JsonUtility is a fast, simple serializer that works with public fields and simple data types but has limitations.
Deserialization creates new objects by default; to update existing objects, use FromJsonOverwrite.
JsonUtility does not support dictionaries, properties, or polymorphism, so alternative libraries may be needed for complex data.
Serialization has performance costs; use it wisely to avoid slowdowns or memory issues in your game.