Unity Online JSON Fetching

Unity Online JSON Fetching


Unity Online JSON Fetching

 Hello friends, in this article I will explain how we can fetch JSON data from our website on the internet using Unity, and in addition, I will mention a website where you can store your JSON data for free.

Additionally, I recommend looking at our other JSON posts.

Unity Creating JSON and Reading JSON

Online JSON Storage Site/Service

On the website with the domain .JSONbin.io, you can share your previously created or site-created JSON files for free and access the JSON files you need for your projects without paying any server fee.

I plan to give more detailed information about this site and its usage later, but for now, I won’t go into too much detail. The only thing you need to know for now is that when you upload it, it gives you an address like this:

"https://api.jsonbin.io/b/5e3602be50a7fe418c57f30c" this is the address of your first uploaded JSON file.

Other than that, according to the number of updates of your uploaded JSON file, you can choose the version you want of the JSON file by adding "/x" with the x number at the end, such as "https://api.jsonbin.io/b/5e3602be50a7fe418c57f30c/1" and "https://api.jsonbin.io/b/5e3602be50a7fe418c57f30c/2". 

If you want to fetch the latest version, it is sufficient to add "/latest" as in "https://api.jsonbin.io/b/5e3602be50a7fe418c57f30c/latest".

Explanation of Fetching JSON Data

To fetch our JSON Data, first we will create 2 C# Scripts: one will contain data types (JSONData) that we will use to parse our JSON file, and the other will contain the code to fetch our JSON file and access it wherever we want (JSONController).

JSONData Script

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

[System.Serializable] // allows jsonDataClass to be accessible from everywhere
public class jsonDataClass
{
    
  public int Version; // Version variable in JSON
  public string AppName; // AppName variable in JSON
    public sorularClass[] Sorular; // We create this for the Sorular array variable in JSON and will fill its content below
}
[System.Serializable] // allows sorularClass to be accessible from everywhere
public class sorularClass
{
    public int No; // No variable in Sorular array in JSON
    public string Soru; // Soru variable in Sorular array in JSON
    public string Dogru_Cevap; // Dogru_Cevap variable in Sorular array in JSON
    public string Yanlis_Cevap1; // Yanlis_Cevap1 variable in Sorular array in JSON
    public string Yanlis_Cevap2; // Yanlis_Cevap2 variable in Sorular array in JSON
    public string Yanlis_Cevap3; // Yanlis_Cevap3 variable in Sorular array in JSON
}

The codes we wrote above name the variables based on the variables we created in JSON when we fetch data from our JSON file. 

Let’s create a sample JSON for better understanding.

While writing the codes above, we created them according to the JSON file below and determined the variable names according to the variable names in the JSON file; the important point here is this, and you must pay attention to this when creating your own 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"}]}

JSONController Script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class jsonController : MonoBehaviour
{
    public bool veriTabaniVarmi = false, Yenile=false; // Variables to check if data exists and to send requests until data arrives if not
    public string jsonURL; // Variable of the site where we will fetch JSON data

    [System.Obsolete] // allows access to jsonDataClass
    void Start()
    {
        jsonURL = "https://api.jsonbin.io/b/5e3602be50a7fe418c57f30c/latest"; // Address where JSON data is located
        StartCoroutine(getData()); // Coroutine function we use to fetch the data
        // NOTE: You need to fetch special functions like IENumerator with Coroutine.
    }

    [System.Obsolete]// allows access to jsonDataClass
    private void Update()
    {
        /* If we could not get the data, allows us to fetch the data again. */
        if (Yenile)
        {
            StartCoroutine(getData());
            Yenile = false;
        }
    }

    [System.Obsolete] // allows access to jsonDataClass
    IEnumerator getData()
    {
        Debug.Log("Wait"); 
        WWW _www = new WWW(jsonURL); // We create the WWW variable and fetch our JSON file.
        yield return _www; // We return the fetched data.
        if (_www.error == null) // If we get no error
        {
            processJsonData(_www.text); // We send the data to be fetched.
            veriTabaniVarmi = true; // We verify that the data is fetched.
        }
        else
        {
            Debug.Log("Error"); // If we cannot fetch the data, we print an error
        }
    }

    public void processJsonData(string _url)
    {
        jsonDataClass jsnData = JsonUtility.FromJson<jsonDataClass>(_url); // We convert the fetched JSON file to the jsonDataClass data type we created.

        Debug.Log("Application name : " + jsnData.AppName); // To fetch AppName variable in JSON data
        
        foreach (sorularClass x in jsnData.Sorular){ // We use this to fetch the Sorular array in the JSON data
            Debug.Log(x.No + "\n");
            Debug.Log(x.Soru + "\n");
            Debug.Log(x.Dogru_Cevap + "\n");
            Debug.Log(x.Yanlis_Cevap1 + "\n");
            Debug.Log(x.Yanlis_Cevap2 + "\n");
            Debug.Log(x.Yanlis_Cevap3 + "\n");
        }
        // If we want to fetch not collectively but individually
         Debug.Log(jsnData.Sorular[0].Soru); 
        /* For Sorular[x] here, you can type a number from 0 up to the max number in your JSON array
        After putting ".", you can enter any variable inside the Sorular class found in jsonDataClass.
        Such as No, Soru, Dogru_Cevap, Yanlis_Cevap1, Yanlis_Cevap2, Yanlis_Cevap3...
        */
        
    }

}

I believe that together with the codes, I have made all the explanations I need to as much as I am able, but if there is any place you get stuck, don’t hesitate to ask questions or leave comments.

Unity Online Json Fetching

Unity Online Json Fetching