Reading Json With Unity


Hello friends, before I explained how to create a JSON file with Unity. For those who have not seen it or want to read it again, you can click the Unity Json Creation link to read the post.

Our JSON File


{
  "Version": 71,
  "AppName": "QuizRun",
  "Sorular": [
    {
      "No": 1,
      "Soru": "Mehmet Akif İstiklal Marşını nerede yazmıtır ?",
      "Dogru_Cevap": "Ankara - Taceddin Dergahı",
      "Yanlis_Cevap1": "Ankara - Keçiören Camisi",
      "Yanlis_Cevap2": "Ankara - Ayaş Dergahı",
      "Yanlis_Cevap3": "Ankara - Ayasofya"
    }, 
   {      "No": 2,
      "Soru": "Mehmet Akif İstiklal Marşını nerede yazmıtır ?",
      "Dogru_Cevap": "Ankara - Taceddin Dergahı",
      "Yanlis_Cevap1": "Ankara - Keçiören Camisi",
      "Yanlis_Cevap2": "Ankara - Ayaş Dergahı",
      "Yanlis_Cevap3": "Ankara - Ayasofya"
    }, 
   {      "No": 3,
      "Soru": "Mehmet Akif İstiklal Marşını nerede yazmıtır ?",
      "Dogru_Cevap": "Ankara - Taceddin Dergahı",
      "Yanlis_Cevap1": "Ankara - Keçiören Camisi",
      "Yanlis_Cevap2": "Ankara - Ayaş Dergahı",
      "Yanlis_Cevap3": "Ankara - Ayasofya"
    }
  ]
}


Fetching JSON Data

General Data File for Fetching JSON Data
First, we need to create a c# file for fetching the data from the ready JSON, I created a c# file called "jsonDataClass".

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class jsonDataClass
{
    
  public int Version;
  public string AppName;
    public sorularClass[] Sorular;
}
[System.Serializable]
public class sorularClass
{
    public int No;
    public string Soru;
    public string Dogru_Cevap;
    public string Yanlis_Cevap1;
    public string Yanlis_Cevap2;
    public string Yanlis_Cevap3;
}


Now, let's explain the codes here.

[System.Serializable]

This code allows us to access the data here from everywhere, then the class we created and the data inside it are the data we will fetch from the JSON file and they must have the same names as in the JSON file. You can check the JSON file above and pay attention to this.

Data Fetching Process

We create a new c# file to fetch the data. I named it "jsonController".

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class jsonController : MonoBehaviour
{
    public bool veriTabaniVarmi = false, Yenile=false;
    public string jsonURL;
    public string soru, dcevap, ycevap1, ycevap2, ycevap3;

    [System.Obsolete]
    void Start()
    {
        StartCoroutine(getData());
    }

    [System.Obsolete]
    private void Update()
    {
        if (Yenile)
        {
            StartCoroutine(getData());
            Yenile = false;
        }
    }

    [System.Obsolete]
    IEnumerator getData()
    {
        Debug.Log("Bekleyin");
        WWW _www = new WWW(jsonURL);
        yield return _www;
        if (_www.error == null)
        {
            processJsonData(_www.text);
            veriTabaniVarmi = true;
        }
        else
        {
            Debug.Log("Hata");
        }
    }

    public void processJsonData(string _url)
    {
        jsonDataClass jsnData = JsonUtility.FromJson(_url);

        int randomSoru = Random.Range(0, jsnData.Sorular.Length);
        soru = jsnData.Sorular[randomSoru].Soru;
        dcevap = jsnData.Sorular[randomSoru].Dogru_Cevap;
        ycevap1 = jsnData.Sorular[randomSoru].Yanlis_Cevap1;
        ycevap2 = jsnData.Sorular[randomSoru].Yanlis_Cevap2;
        ycevap3 = jsnData.Sorular[randomSoru].Yanlis_Cevap3;
    }

}

Now, let's see what we do and where.

[System.Obsolete]
    void Start()
    {
        StartCoroutine(getData());
    }

By adding [System.Obsolete] to the beginning of functions, it allows us to access the data in the "jsonDataClass" I explained above.
StartCroutine is the structure that allows us to fetch data from the internet in Unity and makes the script run when the data comes.

 private void Update()
    {
        if (Yenile)
        {
            StartCoroutine(getData());
            Yenile = false;
        }
    }


Here, we repeated the function call we did in the start() function inside the update() function, because sometimes our data do not arrive instantly when fetching data from the internet and it may be necessary to try a few more times, so we try fetching data until it is retrieved with update.

 IEnumerator getData()
    {
        Debug.Log("Bekleyin");
        WWW _www = new WWW(jsonURL);
        yield return _www;
        if (_www.error == null)
        {
            processJsonData(_www.text);
            veriTabaniVarmi = true;
        }
        else
        {
            Debug.Log("Hata");
        }
    }


Yes friends, here we fetched our JSON file from the internet and if it is not fetched, we made it give an error. I will talk about the WWW command used here in detail in another topic, but for now, I can say that it is a general structure that allows us to fetch data from the internet.

In this post, I showed how to do it via the JSON file's internet URL, and you can do it by writing the internet URL of the JSON where it says jsonURL. If you do not want to fetch the JSON data from the internet and want to fetch the ready data from the folder, you can specify the location of the Json file as Application.dataPath + "JsonDosyasi".json" instead of "jsonURL" above.

By the way, friends, "Application.dataPath" ensures your save file is saved among the game files. (Within the Assets folder on the editor, and within the game's installed folder when you build.)
If you use "Application.persistentDataPath" the created json file is saved to
C: => Users => [user] => AppData => LocalLow => [company name]
location.

Note: To save it to any folder you created inside the game file or locallow, just change the part that says "JsonDosyasi" above to "FolderName/JsonDosyasi" and write the name of the folder you created instead of FolderName.

 public void processJsonData(string _url)
    {
        jsonDataClass jsnData = JsonUtility.FromJson(_url);

        int randomSoru = Random.Range(0, jsnData.Sorular.Length);
        soru = jsnData.Sorular[randomSoru].Soru;
        dcevap = jsnData.Sorular[randomSoru].Dogru_Cevap;
        ycevap1 = jsnData.Sorular[randomSoru].Yanlis_Cevap1;
        ycevap2 = jsnData.Sorular[randomSoru].Yanlis_Cevap2;
        ycevap3 = jsnData.Sorular[randomSoru].Yanlis_Cevap3;
    }


Here we used the ready FromJson function in Unity and converted the fetched json data into c# data. Then we assigned these data to the variables we want. Since I store the questions in my JSON data as a list and I want to fetch one question randomly in each scene, we can randomly fetch a question with the randomSoru part. If we wanted to fetch the Version and AppName in the JSON, all we would have to do is; "jsnData.AppName" or "jsnData.Version" would be enough.
int version;
version = jsnData.Version;

You can fetch any data you want in this way.
You can ask below as a comment if there is anything you wonder or are stuck on.