如何在Unity中获取具有许多变量的JSON数据?

huangapple go评论77阅读模式
英文:

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

问题

我制作了这个代码,可以在API文本中有一个变量及其值时正常工作,但是当文本如下时,我的脚本不起作用,如何修复?我尝试只获取一个变量,但它不起作用,我得到了null。

我的代码可以使用的API文本:https://catfact.ninja/fact

我的代码不能使用的API文本:https://randomuser.me/api

我编辑了代码以从多个变量的JSON中获取数据,但再次得到了null。

英文:

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();
}
}

答案1

得分: 2

在第一个示例中,您正在使用名为“Fact”的类(我假设)具有以下结构(或类似结构):

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

您将JSON反序列化为该对象:

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

但在第二个示例中,响应不同,因此您需要以下类:

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; }
}

// 其他类的翻译...

并使用以下方式进行反序列化:

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

当然,将您的主类的名称更改为您想要的任何名称。

英文:

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&lt;Fact&gt;(webRequest.downloadHandler.text);

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

public class myNewClass
{
    public List&lt;Result&gt; 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&lt;myNewClass&gt;(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/

答案2

得分: 1

如果你只需要一个名称,你可以解析 JSON 字符串并反序列化一个名称属性:

 Name name = JObject.Parse(webRequest.downloadHandler.text)["results"][0]["name"]
                    .ToObject<Name>();
英文:

if you need just a name you can parse a json string and deserilaize a name property

 Name name = JObject.Parse(webRequest.downloadHandler.text)[&quot;results&quot;][0][&quot;name&quot;]
                    .ToObject&lt;Name&gt;();

huangapple
  • 本文由 发表于 2023年4月6日 23:36:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75951308.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定