skip to Main Content

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

I edited code to get data from many variables JSON, 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();
}
}

2

Answers


  1. In the first example you are working with a class "Fact" with (I suppose) this structure (or similar):

    public class Fact
    {
        public string fact { get; set; }
        public int length { get; set; }
    }
    

    and you are deserializating the json to the object with:

     Fact fact = JsonConvert.DeserializeObject<Fact>(webRequest.downloadHandler.text);
    

    but in the second example the response is different, so you need these classes:

    public class myNewClass
    {
        public List<Result> results { get; set; }
        public Info info { get; set; }
    }
    
    public class Coordinates
    {
        public string latitude { get; set; }
        public string longitude { get; set; }
    }
    
    public class Dob
    {
        public DateTime date { get; set; }
        public int age { get; set; }
    }
    
    public class Id
    {
        public string name { get; set; }
        public string value { get; set; }
    }
    
    public class Info
    {
        public string seed { get; set; }
        public int results { get; set; }
        public int page { get; set; }
        public string version { get; set; }
    }
    
    public class Location
    {
        public Street street { get; set; }
        public string city { get; set; }
        public string state { get; set; }
        public string country { get; set; }
        public int postcode { get; set; }
        public Coordinates coordinates { get; set; }
        public Timezone timezone { get; set; }
    }
    
    public class Login
    {
        public string uuid { get; set; }
        public string username { get; set; }
        public string password { get; set; }
        public string salt { get; set; }
        public string md5 { get; set; }
        public string sha1 { get; set; }
        public string sha256 { get; set; }
    }
    
    public class Name
    {
        public string title { get; set; }
        public string first { get; set; }
        public string last { get; set; }
    }
    
    public class Picture
    {
        public string large { get; set; }
        public string medium { get; set; }
        public string thumbnail { get; set; }
    }
    
    public class Registered
    {
        public DateTime date { get; set; }
        public int age { get; set; }
    }
    
    public class Result
    {
        public string gender { get; set; }
        public Name name { get; set; }
        public Location location { get; set; }
        public string email { get; set; }
        public Login login { get; set; }
        public Dob dob { get; set; }
        public Registered registered { get; set; }
        public string phone { get; set; }
        public string cell { get; set; }
        public Id id { get; set; }
        public Picture picture { get; set; }
        public string nat { get; set; }
    }
    
    
    
    public class Street
    {
        public int number { get; set; }
        public string name { get; set; }
    }
    
    public class Timezone
    {
        public string offset { get; set; }
        public string description { get; set; }
    }
    

    and deserializate with:

    myNewClass myDeserializedClass = JsonConvert.DeserializeObject<myNewClass>(webRequest.downloadHandler.text);
    

    of course, change the name of your main class to whatever you want.

    You can work with this or any other case using the following tool:

    https://json2csharp.com/

    Login or Signup to reply.
  2. if you need just a name you can parse a json string and deserilaize a name property

     Name name = JObject.Parse(webRequest.downloadHandler.text)["results"][0]["name"]
                        .ToObject<Name>();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search