Newtonsoft JSON in Unity

👨‍💻 JSON Essentials for Unity Development | Part I

How to Serialize and Deserialize data by using Newtonsoft

Irfan Yigit Baysal
4 min readJan 16, 2024
Json Icon

Introduction

In Unity game development, effective data management is paramount, and JSON (JavaScript Object Notation) emerges as a key player. JSON’s lightweight, readable format facilitates seamless communication within Unity projects, serving tasks like storing configurations and player parameters, managing game state, achievement systems, level editor creations data and so on.

We will use Newtonsoft json in our examples. The reason why I do not use JsonUtility which Unity provides, is its limitations. One of the its limitations are

📌JsonUtility can only serialize and deserialize public fields. It does not work with properties, indexers, or non-public fields.

📌It supports a limited set of types, primarily primitive types (int, float, string, bool) and simple structures.

📌JsonUtility does not support polymorphic serialization, which means it cannot handle cases where you have a base class or interface and multiple derived classes.

However, Newtonsoft provides us wider solutions both functionality and performance.

This brief exploration will delve into JSON’s fundamentals, covering serialization, deserialization, and integration into Unity architectures. Unleash the power of JSON to enhance the flexibility and scalability of your projects, enabling more responsive and data-driven game experiences.

Implementations

Let’s start with a basic example, we will progress by making these more complex and structured in the following articles.

  • Create a struct called ‘Vehicle’.
[Serializable]
public struct Vehicle
{
public string id;
public VehicleType vehicleType;
public double price;
}
  • Define ‘VehicleType’ enum.
public enum VehicleType
{
Default,
Hybrid,
Electric
}

Now we need to two things.

📌 First, we need a Vehicle type reference to set. It may be a only Vehicle or List<Vehicle> or anything you want to. In my example we use as List<Vehicle> type named ‘vehicles’.

📌 Second, we need a string type reference to serialize our Vehicle data. Therefore we also add string type reference named ‘serializedVehicle’ as you see in below.

public class JsonExample : MonoBehaviour
{
[SerializeField] private List<Vehicle> vehicles = new();
[SerializeField] private string serializedVehicle;
}

Let’s go to Unity inspector and set our List<Vehicle> data in editor.

Vehicles Data Settings Image

As I use it as list, I set two vehicle elements as you see above. Now it’s time to implement our method in order to serialize the data into our string.

Serialize

In order to serialize a data we use JsonConvert.SerializeObject(object? value) method. And we set our string to its output.

private void Serialize()
{
serializedVehicle = JsonConvert.SerializeObject(vehicles);
}

You may call this method in editor-time or run-time as suits your project. I will call this method ‘OnValidate’ in editor in order to see the operations quickly. And let’s get back to unity inspector to see the result.

#if UNITY_EDITOR
private void OnValidate()
{
Serialize();
}
#endif
}
Serialize Method Result

As you can see our ‘serializedVehicle’ string is filled. Now this is our serialized vehicle data as json format. So far so good.

Deserialize

In order to serialize a data we use JsonConvert.DeserializeObject<T>(string value) method. In order to see this better let’s define another list called ‘deserializedVehicles

[SerializeField] private List<Vehicle> deserializedVehicles = new();

Now, when we implement the Deserialize method we expect this list to fill according to our ‘serializedVehicle’ string that we filled in our Serialize example above.

private void Deserialize()
{
deserializedVehicles = JsonConvert.DeserializeObject<List<Vehicle>>(serializedVehicle);
}

Let’s get back to unity inspector and see the result.

Deserialize Method Result

As you can see above, the list is filled by ‘serializedVehicle’ value by using Deserialize() method.

Serialize-Deserialize Gif

Summary

We briefly talked about the overall json concept and JsonUtility’s restrictions. We have covered serialization and deserialization by using Newtonsoft json. Although the example here is very simple, it was a good example for us to understand and develop this concept.
See you in Part II 👋

Links That You Want Check

--

--

Irfan Yigit Baysal
Irfan Yigit Baysal

Written by Irfan Yigit Baysal

Unity Game Developer at Matchingham Games

No responses yet