Comprehensive Guide to JSON and JSON Array Serialization and Deserialization in Unity

Nov 23, 2025 · Programming · 13 views · 7.8

Keywords: Unity | JSON | Serialization | Deserialization | C# | Game Development

Abstract: This technical paper provides an in-depth exploration of JSON data serialization and deserialization techniques in Unity, focusing on JsonUtility usage, array handling methods, and common problem solutions. Through detailed code examples and step-by-step explanations, developers will master core skills for efficient JSON data processing in Unity, including serialization/deserialization of single objects and arrays, JsonHelper implementation, and best practices for handling special JSON structures.

Introduction

In modern game development, JSON data format is widely used for network communication and data storage due to its lightweight nature and readability. Unity, as a mainstream game development engine, provides built-in JsonUtility tools for handling JSON data. However, many developers encounter various issues when processing JSON arrays. This paper provides comprehensive guidance through detailed examples and in-depth analysis to help readers master JSON processing techniques in Unity.

JsonUtility Fundamentals

Unity has included the JsonUtility API since version 5.3.3, which is a lightweight JSON serialization tool. Compared to third-party libraries, JsonUtility offers significant performance advantages, though its functionality is relatively simple, primarily supporting basic data types and List arrays.

First, we need to define a serializable data class:

[Serializable]
public class Player
{
    public string playerId;
    public string playerLoc;
    public string playerNick;
}

Note: JsonUtility does not support properties ({ get; set; }), only public fields can be used. Additionally, the class must be marked with the [Serializable] attribute.

Single Object Serialization and Deserialization

Serialization Operations

Converting objects to JSON strings can be done in two ways: basic format and pretty-printed format.

Player playerInstance = new Player();
playerInstance.playerId = "8484239823";
playerInstance.playerLoc = "Powai";
playerInstance.playerNick = "Random Nick";

// Basic format serialization
string playerToJson = JsonUtility.ToJson(playerInstance);
Debug.Log(playerToJson);
// Output: {"playerId":"8484239823","playerLoc":"Powai","playerNick":"Random Nick"}

// Pretty-printed serialization
string playerToJsonPretty = JsonUtility.ToJson(playerInstance, true);
Debug.Log(playerToJsonPretty);
// Outputs formatted JSON

Deserialization Operations

There are three main methods for restoring objects from JSON strings:

// Method 1: Generic deserialization
string jsonString = "{\"playerId\":\"8484239823\",\"playerLoc\":\"Powai\",\"playerNick\":\"Random Nick\"}";
Player player = JsonUtility.FromJson<Player>(jsonString);
Debug.Log(player.playerLoc);

// Method 2: Type-based deserialization
Player player = (Player)JsonUtility.FromJson(jsonString, typeof(Player));
Debug.Log(player.playerLoc);

// Method 3: Overwrite deserialization (recommended for performance optimization)
Player playerInstance = new Player();
void DeserializeData()
{
    string jsonString = "{\"playerId\":\"8484239823\",\"playerLoc\":\"Powai\",\"playerNick\":\"Random Nick\"}";
    JsonUtility.FromJsonOverwrite(jsonString, playerInstance);
    Debug.Log(playerInstance.playerLoc);
}

Overwrite deserialization (FromJsonOverwrite) does not create new object instances but reuses existing instances and overwrites their field values, which significantly reduces memory allocation in scenarios requiring frequent deserialization.

JSON Array Handling

JsonUtility itself does not support direct serialization of top-level arrays, but this functionality can be achieved through helper classes. Here's the complete JsonHelper implementation:

public static class JsonHelper
{
    public static T[] FromJson<T>(string json)
    {
        Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(json);
        return wrapper.Items;
    }

    public static string ToJson<T>(T[] array)
    {
        Wrapper<T> wrapper = new Wrapper<T>();
        wrapper.Items = array;
        return JsonUtility.ToJson(wrapper);
    }

    public static string ToJson<T>(T[] array, bool prettyPrint)
    {
        Wrapper<T> wrapper = new Wrapper<T>();
        wrapper.Items = array;
        return JsonUtility.ToJson(wrapper, prettyPrint);
    }

    [Serializable]
    private class Wrapper<T>
    {
        public T[] Items;
    }
}

Array Serialization Example

Player[] playerInstance = new Player[2];

playerInstance[0] = new Player();
playerInstance[0].playerId = "8484239823";
playerInstance[0].playerLoc = "Powai";
playerInstance[0].playerNick = "Random Nick";

playerInstance[1] = new Player();
playerInstance[1].playerId = "512343283";
playerInstance[1].playerLoc = "User2";
playerInstance[1].playerNick = "Rand Nick 2";

// Convert to JSON array
string playerToJson = JsonHelper.ToJson(playerInstance, true);
Debug.Log(playerToJson);

Array Deserialization Example

For JSON arrays received from servers, format conversion is required first:

string fixJson(string value)
{
    value = "{\"Items\":" + value + "}";
    return value;
}

// Usage example
string serviceData = "[{\"playerId\":\"1\",\"playerLoc\":\"Powai\"},{\"playerId\":\"2\",\"playerLoc\":\"Andheri\"},{\"playerId\":\"3\",\"playerLoc\":\"Churchgate\"}]";
string fixedJson = fixJson(serviceData);
Player[] players = JsonHelper.FromJson<Player>(fixedJson);

// Iterate through array to access data
for (int i = 0; i < players.Length; i++)
{
    Debug.Log($"Player {i}: ID={players[i].playerId}, Location={players[i].playerLoc}");
}

Handling Special JSON Structures

When JSON contains property names starting with numbers or other special structures, JsonUtility may not handle them directly. For example:

{
    "USD": {\"15m\": 1740.01, "last": 1740.01},
    "ISK": {\"15m\": 179479.11, "last": 179479.11}
}

The property "15m" starts with a number, which is invalid for C# class variables. In such cases, third-party libraries like SimpleJSON can be used:

var N = JSON.Parse(yourJsonString);
string price = N["USD"]["15m"].Value;
Debug.Log(price);

Common Issues and Solutions

Serialization Problems

If JsonUtility.ToJson returns empty string or "{}":

Deserialization Problems

If JsonUtility.FromJson returns null:

Performance Optimization Recommendations

In performance-sensitive scenarios:

Third-Party Library Options

While JsonUtility meets most requirements, third-party libraries may be necessary for complex scenarios:

Unity now provides official Newtonsoft.Json support through the package manager, accessible by adding the "com.unity.nuget.newtonsoft-json" package.

Conclusion

JSON processing in Unity, while seemingly straightforward, requires attention to numerous details in practical applications. By properly utilizing JsonUtility and JsonHelper, developers can efficiently handle most JSON serialization requirements. For special scenarios, selecting appropriate third-party libraries provides better flexibility and functionality support. Mastering these techniques will significantly enhance development efficiency and data processing capabilities in Unity projects.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.