Newtonsoft JSON in Unity
👨💻 JSON Essentials for Unity Development | Part II
Formatting Json to get better visualization by using Newtonsoft
Introduction
In previous Json article (JSON Essentials for Unity Development | Part I) we discussed and exemplied Json usage in Unity development. We briefly covered serialization and deserialization concept with some implementations. In this article we are going to cover Json formatting to get better visualization while reading the data. In order to make this happen we are going to use JsonSerializerSettings provided by Newtonsoft.
Implementation
Let’s first create a JsonSerializerSettings named ‘settings’.
JsonSerializerSettings settings = new JsonSerializerSettings();
In JsonSerializerSettings, there are many options to modify the json data as enum type. I strongly recommend to check the source code. We only use ‘Formatting’ enum for now.
There are 2 Formatting options which are
📌 None
📌 Indented
settings.Formatting = Formatting.Indented;
You may also implement this code like this below as a small reminder :)
JsonSerializerSettings settings = new JsonSerializerSettings()
{
Formatting = Formatting.Indented
};
Now we need to two things to complete our formatting modification. We need to
📌 Create JToken to set deserialized json data with the JsonSerializerSettings
📌 Serialize this token into our string that holds the json data.
Remember ‘serializedVehicle’ string in our first article (JSON Essentials for Unity Development | Part I)
JToken jToken = JsonConvert.DeserializeObject<JToken>(serializedVehicle, settings);
Now we have jToken that holds the serializedVehicle with the settings we modified. Lastly we serialize this token into the serializedVehicle or create new string to hold it.
serializedVehicle = JsonConvert.SerializeObject(jToken, settings);
Now that we have examined and summarized them one by one, we can turn what we have done into a method.
public void BeautifyJson()
{
JsonSerializerSettings settings = new JsonSerializerSettings()
{
Formatting = Formatting.Indented
};
JToken jToken = JsonConvert.DeserializeObject<JToken>(serializedVehicle, settings);
serializedVehicle = JsonConvert.SerializeObject(jToken, settings);
}
Lastly, To make a comparison, let’s print the formatted and unformatted version as a log into the Start method and examine it.
private void Start()
{
Debug.Log($"Unformatted :{serializedVehicle}");
BeautifyJson();
Debug.Log($"Formatted : {serializedVehicle}");
}
By formatting it, we achieved a more organized and readable appearance. You can also print this to text or another file in your project.
Summary
We have covered JsonSerializerSettings to modify our json data. We have used Formatting settings to beautify our output the get better visualization. We talked about how important this reading can be as the data grows and takes shape and more different types are added.
See you in Part III 👋