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

  • 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.
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Akarsh SEGGEMU

Akarsh SEGGEMU

24 Followers

Software Engineer (Android, iOS, Unity) | M.Sc. Computer Science — Technische Universitaet Berlin | Mobile Advertising, Attribution, Monetisation, UA & Analytic