Built-in Way of Working with JSON in Unity Code

JSON (JavaScript Object Notation) is a widely used data interchange format, and integrating it into Unity can be powerful for handling configurations, saving game progress, or exchanging data with external services. This guide walks you through the fundamentals of working with JSON in Unity.

Step 1: Understanding JSON

JSON consists of key-value pairs and nested structures.

Step 2: Working with JSON in Unity Code

Unity simplifies JSON serialization and deserialization through its 'JsonUtility' class. This guide demonstrates the basic steps to work with JSON in Unity without external libraries.

  • Create a JSON Structure:
{
  "playerName": "John Doe",
  "playerLevel": 5,
  "inventory": ["sword", "shield"]
}
  • Serialization - Converting C# Object to JSON:
using UnityEngine;

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

public class SerializationExample : MonoBehaviour
{
    void Start()
    {
        PlayerData playerData = new PlayerData
        {
            playerName = "John Doe",
            playerLevel = 5,
            inventory = new string[] { "sword", "shield" }
        };

        string json = JsonUtility.ToJson(playerData);
        Debug.Log(json);
    }
}
  • Deserialization - Converting JSON to C# Object:
using UnityEngine;

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

public class DeserializationExample : MonoBehaviour
{
    void Start()
    {
        string jsonData = "{\"playerName\":\"John Doe\",\"playerLevel\":5,\"inventory\":[\"sword\",\"shield\"]}";
        PlayerData playerData = JsonUtility.FromJson<PlayerData>(jsonData);

        Debug.Log($"Name: {playerData.playerName}, Level: {playerData.playerLevel}");
        Debug.Log("Inventory: " + string.Join(", ", playerData.inventory));
    }
}

Known Limitations

'JsonUtility' does not directly support the serialization and deserialization of top-level arrays of objects (e.g., '[{},{},{}]') without a wrapping class. To work around this, you can use a helper class to wrap the array. Here's an example:

using UnityEngine;

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

[System.Serializable]
public class PlayerDataArrayWrapper
{
    public PlayerData[] players;
}

public class TopLevelArrayExample : MonoBehaviour
{
    void Start()
    {
        // Serialization: Converting C# Object Array to JSON
        PlayerData[] players = new PlayerData[]
        {
            new PlayerData { playerName = "John Doe", playerLevel = 5 },
            new PlayerData { playerName = "Jane Smith", playerLevel = 8 }
        };

        PlayerDataArrayWrapper wrapper = new PlayerDataArrayWrapper { players = players };
        string json = JsonUtility.ToJson(wrapper);
        Debug.Log(json);

        // Deserialization: Converting JSON to C# Object Array
        string jsonData = "{\"players\":[{\"playerName\":\"John Doe\",\"playerLevel\":5},{\"playerName\":\"Jane Smith\",\"playerLevel\":8}]}";
        PlayerDataArrayWrapper deserializedData = JsonUtility.FromJson<PlayerDataArrayWrapper>(jsonData);

        foreach (var player in deserializedData.players)
        {
            Debug.Log($"Name: {player.playerName}, Level: {player.playerLevel}");
        }
    }
}

In the example above, the 'PlayerDataArrayWrapper' class is used to wrap the array when serializing and deserializing. It's a common practice to create such wrapper classes when dealing with top-level arrays of objects in 'JsonUtility'.

Conclusion

'JsonUtility' simplifies JSON serialization and deserialization directly without external libraries. Use this native approach for straightforward JSON operations in Unity projects.

Suggested Articles
Working with Arrays and Lists in Unity Code
Creating a Pac-Man-Inspired Game in Unity
Working with Strings and Manipulating Text Data in Unity
Guide to MonoBehaviour in Unity
Unity Obfuscation Methods and Anti-Hack Protection
A Guide to Integrating Nintendo Controller with Unity
Top Useful Code Snippets for Unity Developers