JSON Serializer

Jason

Unity added the JsonUtility class to version 5.3. It does not require attributes and is faster than my serializer. So let’s be honest with each other, you should use the JsonUtility if you are on Unity5.3. If you think 5.3 is too buggy (and damn it still is even after 3 months in…) and you wish to stay on older version, then go ahead.

You can download the file from JSONSerializer.

This is just a use case, for some tutoring on how it works, check that article.

The file contains the JSON parser and serializer.

TESTED AND WORKING ON : Editor, iOS, Android, WebGl.

07/10/2015 : version1.1: Fixed issue on C# object not existing in the file, added support for Color, Vector2/3/4.

14/10/2015 : version1.2: Added support for Enum.

What the serializer does not consider:

  • Other collections such as List, IList, you can always convert the array to the needed continuous type.

  • Quaternion since you can convert from Vector4 that is supported.

Example

Let’s use a basic class with a basic json file and create the matching class.

{
    "id": 1,
    "name": "James Cameron",
    "director": true,
    "movie": [
        {
            "title": "Terminator",
            "status": "plagiat",
            "originalwriter":"Harlan Ellison"
        },
        {
            "title": "Avatar",
            "status": "plagiat",
            "originalstory": "Pocahontas";
        }
    ]
}
// Different script
using JSON;
[System.Serializable]
public class Person
{
    [JSONItem("id",typeof(int))]
    public int id = 0;
    [JSONItem("name", typeof(string))]
    public string name = "name";
    [JSONItem("director", typeof(bool))]
    public int age = 0;
    [JSONArray("movie", typeof(Movie))]
    public Movie[] movie;
}
[System.Serializable]
public class Movie
{
    [JSONItem("title", typeof(string))]
    public string title = null;
    [JSONItem("status", typeof(string))]
    public string status = null;
    [JSONItem("originalstory", typeof(string))]
    public string originalstory = null;
    [JSONItem("originalwriter", typeof(string))]
    public string originalwriter = null;
}

Create the json file on a text editor like notepad and remember to change the extension to .json. Then place it on the Asset folder, not anywhere down or change the path.

Notice the type for Movie[] is actually only given as Movie. The array nature comes from the attribute.

// other usings
using JSON;

public class JsonTest : MonoBehaviour
{
    [SerializeField] private Person person = null;
	private void Start ()
    {
        string json = File.ReadAllText(Path.Combine(Application.dataPath, "config.json"));
        this.person = (Person)JSONSerialize.Deserialize(typeof(Person), json);
	}
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            JSONSerialize.Serialize(Path.Combine(Application.dataPath, "configNew.json"), this.person);
        }
    }
}

Since the serializer can return arrays, there is no real need for List or IList since you can convert from array to any needed type.

And this is it basically. Run the program, you will see the value in the Inspector, you can change them and press space, there will be a new json file called configNew that will hold the new value (it will be all on one line).

Here is another example where you access a value by code and using generic version..

using JSON;

public class JsonTest : MonoBehaviour
{
    [SerializeField] private Person person = null;
    private void Start ()
    {
        string json = File.ReadAllText(Path.Combine(Application.dataPath, "config.json"));
        this.person = JSONSerialize.Deserialize<Person>( json);
        this.person.movie[0].name = "Other title";
        Movie movieRef = this.person.movie[1];
        // movieRef points to the second movie object about avatar
    }
}

You can also grab parts of the json file:

public class JsonTest : MonoBehaviour
{
    [SerializeField] private Movie movie = null;
    private void Start ()
    {
        string json = File.ReadAllText(Path.Combine(Application.dataPath, "config.json"));
        JSONObject jsonObject  = JSONObject.Parse(json);
        JSONArray jsonArrayMovie = jsonObject.GetArray("movie");
        JSONObject firstMovieObject = jsonArrayMovie[0];
        this.movie = JSONSerialize.Deserialize<Movie>(firstMovieObject.ToString());
    }
}

There is not much more to say about it. It is still a work in progress so if you could provide feedbacks.

It is not yet including a loooot of features I will work on later, such as ability to parse Vector2/3/4, Quaternion and other usual classes and structs, deserialize to Dictionary and more.
Please if you encounter a crash or issue or would recommend a feature, let me know so I can improve and if possible avoid starting with something like:”This is prapa rabbish mate. Absolut garbage of asset crashing when I try to use it wrong.” More likely “Kind sir, I found a bug and a missing feature I wish to report”.

Enjoy.

1 Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s