Unity and JSON – Quick Guide

I’m not a big fan of XML. It’s a bit heavy and dense, and though it’s effective, I just prefer JSON.

Introduction

But what IS Json? Well I’m not going to cover that, but some people smarter than I have already answered that question, so have a look over here and come back when you’re done.

If you’ve never used it, it may take a while to wrap your head around the inception-like dictionary-within-a-dictionary structure. But after you serialize and deserialize some data, you’ll get an idea of how it works.

Unity doesn’t have a built in solution for JSON. Though Unity supports JavaScript, it’s not quite the  same flavor you may have run across in web programming, it’s actually a different language, which is why more and more people are calling it UnityScript, instead. Why do I bring this up? Well, we can’t just use existing JavaScript libraries to incorporate JSON. There are alternatives, though! Let’s explore…

Get Dark Table’s JsonFX

Dark Table has created a nifty JSON solution for Unity, JsonFx.  You can grab the DLL here, if you want to follow along.

Once you’ve downloaded it, go ahead and drop the DLL into your project. I chose to drop it in a folder called Extensions.

Our Data Classes

The readme file that comes in the JsonFx zip file has a list of supported data types. We’ll keep it simple with some primitives and an array–just to demonstrate the functionality.

I’ve created a couple of classes for this example. We have one called DataPC, which is just information we’re going to store for our Player Controller. This is just personal preference (and how I learned), but I name classes I intend to serialize DataName . I refer to these as data classes, since their purpose is to be conduits for my JSON files, not the actual classes. In other words, I’ll probably have a class called PC to handle in-game functionality, but my DataPC class simple helps store and retrieve data as JSON. This isn’t required by any means, it’s just a convention i have stuck to.

The second class I created is a DataItem class, which stores item-specific data.

public class DataPC
{
    public string name;
    public int maxLevel;
    public string description;
    public string portrait;

    public DataItem[] inventory;
}

public class DataItem
{
    public string name;
    public int cost;
}
									

We’re getting a little fancy here: I created a DataItem array to store multiple items. You’ll see how this looks in JSON next.

Serializing the Data

Next, I’ve set up a class to handle serialization and deserialization. This is probably not the way you’d ever implement either of these, but we’re just trying to get to the results, so here ya go:

using UnityEngine;
using System.Collections;
using JsonFx.Json;

public class DataHandlerTest : MonoBehaviour 
{
    public DataPC myPC;
    void Start()
    {
        myPC = new DataPC();
        myPC.name = "Jimbob";
        myPC.maxLevel = 99;
        myPC.description = "Jimbob likes beer and trucks.";
        myPC.portrait = "jimbob.png";
        myPC.inventory = new DataItem[2];

        myPC.inventory[0] = new DataItem();
        myPC.inventory[1] = new DataItem();

        myPC.inventory[0].name = "Silver Bullet";
        myPC.inventory[0].cost = 5;

        myPC.inventory[1].name = "Shotgun";
        myPC.inventory[1].cost = 200;
    }

    public void OnGUI()
    {
        if (GUILayout.Button("SERIALIZE"))
        {
            string myJson = JsonWriter.Serialize(myPC);
            Debug.Log(myJson);
        }
    }
}

									

First thing to notice is that we need to include the JsonFx library: using JsonFx.Json

Next, we create a new instance of DataPC and initialize its values. We give it two items in its inventory array and initialize each of those.

The meat and potatoes is in the OnGUI() method.

string myJson = JsonWriter.Serialize(myPC);
Debug.Log(myJson);
									

What we’re doing here is serializing the class into Json and saving that Json into a string. Once we have the string, we print it out to the debug log.

One small issue with this method is that it generates a line of JSON. No formatting. This means it’s kinda hard to read when there’s a lot of data, but you can throw this into the text editor of your choice and use its formatting to make the Json readable. You can also use a web-based tool to do it such as this one. This will format and verify the Json  for you. So let’s see what we got:

{
   "name":"Jimbob",
   "maxLevel":99,
   "description":"Jimbob likes beer and trucks.",
   "portrait":"jimbob.png",
   "inventory":[
      {
         "name":"Silver Bullet",
         "cost":5
      },
      {
         "name":"Shotgun",
         "cost":200
      }
   ]
}
									

Let’s break it down. The main document is a dictionary. It contains entries that correspond to our instance variables. name, maxLevel, etc. Our DataItem array got turned into an array of dictionaries, each with their own keys/values for the variables inside the DataItem.

So, now we have our Json in a string. Whoop-dee-doo. That isn’t all that useful to us.  You are correct, but we’re out of time for this tutorial. In the next part, we’ll save this data to a text file, then read off that file and Deserialize back into our DataPC and DataITem classes.

FacebookTwitterGoogle+Share

Leave a Reply