Categories
Scripting Tips Unity

JSON De/Serialization Using Unity and JsonFx

Difficulty: Medium

My previous JSON tutorial was a while ago, and it never covered actually deserializing data (but is still useful on it’s own), so rather than doing the second half on its own, this tutorial will cover all the steps from the beginning using  JsonFx.

∗ This guide is tested as of Unity 4.3.4f

 

Purpose

The purpose of serializing data is so that it can be stored or shared across different systems, or even applications. It creates a common data template that can be converted back and forth (serialized and deserialized) even when the source data is not one that is understood by the receiving system or application natively. There are various common formats that can be used (i.e XML, CSV,  Binary, or in our case, JSON), to serialize data into.

In our example, we’re going to create a class that lives within our application; a Sandwich. When we create an instance of it, it will exist in memory until we destroy it or the app is stopped. Once we turn off play mode in the unity editor (or close our window in a build), that data is gone. By serializing it, in this case to a text file using JSON, not only can we store it to the file system, but we can edit it offline and see the changes reflected in our application when we load it up again. This is all sort of odd-sounding without seeing it in action, so let’s get to it.