How to get JSON data that has many variables in it?

I made this code that works when API text has one variable and it’s value, but when text is like this my script doesn’t work, how to fix it? I tryed to get only one variable but it didn’t work and i got null.

API text that my code work with: https://catfact.ninja/fact

API text that my code does not work with: https://randomuser.me/api

Code:

using UnityEngine;
using TMPro;
using UnityEngine.Networking;
using System.Collections;
using System;
using Newtonsoft.Json;

public class Service : MonoBehaviour
{
    [SerializeField] private TextMeshProUGUI _text;

    private void Start()
    {
        StartCoroutine(GetRequest("https://randomuser.me/api"));
    }

    private IEnumerator GetRequest(String url)
    {
        using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
        {
            yield return webRequest.SendWebRequest();

            switch (webRequest.result)
            {
                case UnityWebRequest.Result.ConnectionError:
                case UnityWebRequest.Result.DataProcessingError:
                _text.text = "Error: " + webRequest.error;
                break;

                case UnityWebRequest.Result.ProtocolError:
                _text.text = "HTTP Error: " + webRequest.error;
                break;

                case UnityWebRequest.Result.Success:
                if (CheckAPI(webRequest))
                {
                    Fact fact = JsonConvert.DeserializeObject<Fact>(webRequest.downloadHandler.text);

                    if (fact.results == null)
                    {
                        _text.text = "Error: no information with such variables";
                    }
                    else
                    {
                        _text.text = fact.results;
                    }
                }
                else
                {
                    _text.text = "Error: there are no API data";
                }
                break;
            }
        }
    }

    private bool CheckAPI(UnityWebRequest data)
    {
        string contentType = data.GetResponseHeader("Content-Type");

        if (!string.IsNullOrEmpty(contentType) && contentType.Contains("application/json"))
        {
            return true;
        }
        else
        {
            return false;

        }
    }
    public class Fact
    {
        public string results { get; set; }
    }

    public void NewRequest()
    {
        Start();
    }
}

Goto json2csharp.com

1 Like

I tryed with Name but again got null.

using UnityEngine;
using TMPro;
using UnityEngine.Networking;
using System.Collections;
using System;
using Newtonsoft.Json;

public class Service : MonoBehaviour
{
    [SerializeField] private TextMeshProUGUI _text;

    private void Start()
    {
        StartCoroutine(GetRequest("https://randomuser.me/api"));
    }

    private IEnumerator GetRequest(String url)
    {
        using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
        {
            yield return webRequest.SendWebRequest();

            switch (webRequest.result)
            {
                case UnityWebRequest.Result.ConnectionError:
                case UnityWebRequest.Result.DataProcessingError:
                _text.text = "Error: " + webRequest.error;
                break;

                case UnityWebRequest.Result.ProtocolError:
                _text.text = "HTTP Error: " + webRequest.error;
                break;

                case UnityWebRequest.Result.Success:
                if (CheckAPI(webRequest))
                {
                    Name name = JsonConvert.DeserializeObject<Name>(webRequest.downloadHandler.text);

                    if (name.title == null || name.first == null || name.last == null)
                    {
                        _text.text = "Error: no information with such variables";
                    }
                    else
                    {
                        _text.text = name.title + " " + name.first + " " + name.last;
                    }
                }
                else
                {
                    _text.text = "Error: there are no API data";
                }
                break;
            }
        }
    }

    private bool CheckAPI(UnityWebRequest data)
    {
        string contentType = data.GetResponseHeader("Content-Type");

        if (!string.IsNullOrEmpty(contentType) && contentType.Contains("application/json"))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public class Name
    {
        public string title { get; set; }
        public string first { get; set; }
        public string last { get; set; }
    }

    public void NewRequest()
    {
        Start();
    }
}

The answer is always the same:

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Three steps to success:

  • Identify what is null ← any other action taken before this step is WASTED TIME
  • Identify why it is null
  • Fix that

More on JSON:

Problems with Unity “tiny lite” built-in JSON:

In general I highly suggest staying away from Unity’s JSON “tiny lite” package. It’s really not very capable at all and will silently fail on very common data structures, such as bare arrays, tuples, Dictionaries and Hashes and ALL properties.

Instead grab Newtonsoft JSON .NET off the asset store for free, or else install it from the Unity Package Manager (Window → Package Manager).

Also, always be sure to leverage sites like:

https://csharp2json.io

You tried with Name? No, you have to read the structure as it is. You have to read the “Root” class that json2csharp.com gave you. You may remove information you don’t need, but you can not directly jump to some nested information. Json is a structured hierachical data structure.

If you’re only interested in reading certain values, you may want to use my SimpleJSON framework which is just a single file and doesn’t require you to create any additional classes. It does not do any object mapping. Instead the json data is simply represented as abstract objects / arrays or “nodes” and you can simply traverse the structure.

using SimpleJSON;

// [ ... ]

var root = JSON.Parse(yourJsonString);
string firstName = root["results"][0]["name"]["first"];
string firstName = root["results"][0]["name"]["last"];
1 Like