CSharp: How to create JSON Object and JSON String in Unity C#

Akarsh Seggemu
2 min readFeb 22, 2022

JSON is mostly preferred format in sending and receiving data in client-side applications to back-end-severs.

If you are developing applications in Unity using C# you can use JsonUtility which is part of the UnityEngine.JSONSerializeModule to work with Json data. JsonUtility does not require you to add any third party libraries to your Unity project. Reducing the usage of third party libraries also improves in maintenance of the project as you don’t to spend time in updating third-party libraries in your Unity project.

Here is how you can use JsonUtility in your Unity project,

  • Creation of string from Json data.
    For example, consider a Json data which contains details of a city object is saved in string data type.
using UnityEngine;

public class City : MonoBehaviour
{
public string cityName;
public int districts;
public float income;

public string SaveToString()
{
return JsonUtility.ToJson(this);
}

// Given:
// cityName = "Berlin"
// districts = 12
// income = 90000.87f
// SaveToString returns:
// {"cityName":"Berlin","districts":12,"income":90000.87}
}
  • Creation of an object from Json data.
    For example, consider a Json data which contains details of a city object is saved in object data type.
using UnityEngine;

[System.Serializable]
public class City
{
public string cityName;
public int districts;
public float income;

public static City CreateFromJSON(string jsonString)
{
return JsonUtility.FromJson<City>(jsonString);
}

// Given JSON input:
// {"cityName":"Berlin","districts":12,"income":90000.87}
// this example will return a City object with
// cityName = "Berlin", districts = 12, and income = 90000.87f.
}

I hope my article helps you understand how to work with Json data in Unity.

If you like my articles, please follow me.

You can also support me by https://www.buymeacoffee.com/akarshseggemu

--

--

Akarsh Seggemu

IT Team Lead | MSc in Computer Science from Technische Universität Berlin | Writing articles to Empower Software Engineers and IT Leaders