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
In the first example you are working with a class "Fact" with (I suppose) this structure (or similar):
and you are deserializating the json to the object with:
but in the second example the response is different, so you need these classes:
and deserializate with:
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/
if you need just a name you can parse a json string and deserilaize a name property