JSON with Unity

Unity Internal Serializer

The standard serializer is tricky. Read it like this:


and write it like this:

[Serializable]
public class GlassesKeypointData
{
    public List<int> vertexIDs = new List<int>();
}

public class JsonWriter
{
    public void GetJson()
    {
        GlassesKeypointData temp = new GlassesKeypointData();
        temp.ids=new List<int>(){1, 2, 3, 4, 5};
        string myString = JsonUtility.ToJson(temp, true);
        Debug.Log(myString);
    }
}

Gives you this:

{
    "ids": [
        1,
        2,
        3,
        4,
        5
    ]
}

Newtonsoft JSON Serializer

This is a much more versatile API.

// using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;

public class JsonDemo
{
    Dictionary<int, string> myDataStructure;
    string jsonpath = @"C:\temp\myJsonFile.json";

    public void WriteDemoJson()
    {
        // some Demo Data
        myDataStructure = new Dictionary<int, string>();
        myDataStructure.Add(1,"My value");

        // Setup the serializer
        JsonSerializer serializer = new JsonSerializer();
        serializer.NullValueHandling = NullValueHandling.Ignore;
        serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        serializer.Formatting = Formatting.Indented;

        // Write our data
        using (StreamWriter sw = new StreamWriter(jsonpath))
            using (JsonWriter writer = new JsonTextWriter(sw))
                serializer.Serialize(writer, myDataStructure);
    }

    public void ReadDemoJson()
    {
        using (StreamReader file = File.OpenText(jsonpath))
        {
            JsonSerializer serializer = new JsonSerializer();
            myDataStructure = (Dictionary<int, string>)serializer.Deserialize(
                                file, typeof(Dictionary<int, string>));
        }
    }
}