JSON data in Unity

Json logo

The project that I am currently working on calls for being able to parse JSON data in Unity. Now, you may be thinking, “There is an actual documentation page on this”, and you are not wrong. In fact, it’s right here.

However, if you are new to JSON and the utility in Unity, then it can be a bit confusing to set up the C# code with more complex JSON data.

example output
Example output from my Log Files

As you can see, there are a couple ‘children’ in this JSON data like “_source” and “beat”, and also an array called “hits”.  To set this up in C# is very simple, but it is lacking the actual Unity Documentation.

public class Json_Data
 public int took;
 public bool timed_out;
 public HitsParent hits; 

public class HitsParent
 public int total;
 public HitsData[] hits;

public class HitsData
 public string _index;
 public string _type;
 public string _id;
 public Source _source;

Make sure that each variable’s name in C# matches with the JSON field name, or it will actually mark all the variables that come after that as null.

Take note that it is bad practice to have multiple classes within the same file, but for JSON it is a bit cleaner to put it all in one class if you will have multiple data types.

Every class needs to be serialize, because that is how Unity parses the data. To learn more about why each class needs to be Serializable, go to the Unity documentation.

Author: Ben Hoffman

RIT Game Design and Development student