Unity 5.3 Using JSON Serialization

Saving and loading data in Unity just got easier with the most widely used formats for transferring data on the web. JSON provides a simple easy to read object notation syntax for exchanging data. With the addition of the new JsonUtility class you now have access to using JSON in Unity.

Unity JSON Support
Unity JSON Support

Getting Started with JSON

As of version 5.3 Unity now supports the ability for loading and saving data in JSON format. Popularized for its ease of use, readability and transport JSON has long been the choice of many developers.

As part of the new JsonUtility class you now have access to 3 methods for working with JSON in Unity

  1. Generating JSON string from serializable class (including Monobehavior)
  2. Converting JSON string to accessible object
  3. Converting JSON string and inherit/overwrite current class variables.

Converting to JSON String with JsonUtility.ToJson

When you need to convert an object to a JSON string, use the new JsonUtility.ToJson method; which supports to 2 parameters; object to convert and an optional boolean to return a well-formatted string “which defaults to false”.

[Serializable]
public class LevelData {
	public string name;
	public int order;
	public float time;
}
public class Converter extends Monobehavior {
	public LevelData lv;
	void Start (){
		lv = new LevelData();
		lv.name = "Convert to String";
		lv.order = 1;
		lv. time = 10.0f;	
		//Log string to console window
		Debug.Log(JsonUtility.ToJson(lv))
		//Log 
		Debug.Log(JsonUtility.ToJson(lv, true))
	}
}

In the above example, we have a class LevelData with a Serializable tag(must have for JSON conversion to work) and two Debug.Log statements. The first statement creates a simple unformatted JSON string by calling JsonUtility.ToJson(lv);

{ "name": "Convert to String", "order": "1", "time": "10.0" }

The second Log statement is slightly different; we take advantage of the pretty print option, JsonUtility.ToJson(lv, true); This is useful when you want to read the JSON string in a formatted state instead of the compact version above.

{
	"name": "Convert to String",
	"order": "1", 
	"time": "10.0" 
} 

Converting JSON String to Accessible Object

The first and most important thing to note is, Unity doesn’t assume what the class/object conversion will be instead you are responsible for casting the object on creation. The alternative to this would have been adding class metadata to the JSON string output which would just bloat your code; this method, though adding an extra step, is much more efficient in the long run.

The following example we will use our LevelData class and the outputted JSON string to recreate a LevelData object. As a side note in order for the string to be considered valid for this example I escaped all of the quotation marks (“) with ”.

pubilc class LoadJsonLevel extends Monobehavior {
		public LevelData level;
	void Start(){
		string str = "{ "name": "Convert to String", "order": "1", "time": "10.0" }";
		level = JsonUtility.FromJson<LevelData> (str);
		Debug.Log (level.name ); //displays Convert to String
		// level object now contains JSON string values
	}
}

Casting the JSON conversion object is done by “<LevelData>”in JsonUtility.FromJson<LevelData>. The returned object now populates our level variable. In this example we have access the loaded data in our level variable but what if we wanted to load our data into the current class and overwrite those values.

Converting JSON String and Inherit/Overwrite Current Class Variables

JsonUtility.FromJsonOverwrite allows you to load a JSON string and supply an object to overwrite or replace supported properties. That includes Scriptable Objects; Monobehavior derived classes as well as plain classes and structs with the [Serializable] attribute. In our example, we will replace the line setting the level object with the overwrite method. You can also supply  this pointer as well to affect the current class

pubilc class LoadJsonLevel extends Monobehavior {
		public LevelData level;
	void Start(){
		string str = "{ "name": "Convert to String", "order": "1", "time": "10.0" }";
		 JsonUtility.FromJsonOverwrite(savedData, level);
		Debug.Log (level.name ); //displays Convert to String
		// level object now contains JSON string values
	}
}

Final Thoughts

Best used for transmitting data to and from servers JSON Serialization provides Unity developers with a more familiar format for data management. Not to be limited, JSON can easily be used for user settings, game saves and much more. With any serialization you should test to see how well it performs with your dataset, JSON is now different.