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

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

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:

  1. using UnityEngine;
  2. using TMPro;
  3. using UnityEngine.Networking;
  4. using System.Collections;
  5. using System;
  6. using Newtonsoft.Json;
  7. public class Service : MonoBehaviour
  8. {
  9. [SerializeField] private TextMeshProUGUI _text;
  10. private void Start()
  11. {
  12. StartCoroutine(GetRequest("https://randomuser.me/api"));
  13. }
  14. private IEnumerator GetRequest(String url)
  15. {
  16. using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
  17. {
  18. yield return webRequest.SendWebRequest();
  19. switch (webRequest.result)
  20. {
  21. case UnityWebRequest.Result.ConnectionError:
  22. case UnityWebRequest.Result.DataProcessingError:
  23. _text.text = "Error: " + webRequest.error;
  24. break;
  25. case UnityWebRequest.Result.ProtocolError:
  26. _text.text = "HTTP Error: " + webRequest.error;
  27. break;
  28. case UnityWebRequest.Result.Success:
  29. if (CheckAPI(webRequest))
  30. {
  31. Name name = JsonConvert.DeserializeObject<Name>(webRequest.downloadHandler.text);
  32. if (name.title == null || name.first == null || name.last == null)
  33. {
  34. _text.text = "Error: no information with such variables";
  35. }
  36. else
  37. {
  38. _text.text = name.title + " " + name.first + " " + name.last;
  39. }
  40. }
  41. else
  42. {
  43. _text.text = "Error: there are no API data";
  44. }
  45. break;
  46. }
  47. }
  48. }
  49. private bool CheckAPI(UnityWebRequest data)
  50. {
  51. string contentType = data.GetResponseHeader("Content-Type");
  52. if (!string.IsNullOrEmpty(contentType) && contentType.Contains("application/json"))
  53. {
  54. return true;
  55. }
  56. else
  57. {
  58. return false;
  59. }
  60. }
  61. public class Name
  62. {
  63. public string title { get; set; }
  64. public string first { get; set; }
  65. public string last { get; set; }
  66. }
  67. public void NewRequest()
  68. {
  69. Start();
  70. }
  71. }

答案1

得分: 2

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

  1. public class Fact
  2. {
  3. public string fact { get; set; }
  4. public int length { get; set; }
  5. }

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

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

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

  1. public class myNewClass
  2. {
  3. public List<Result> results { get; set; }
  4. public Info info { get; set; }
  5. }
  6. public class Coordinates
  7. {
  8. public string latitude { get; set; }
  9. public string longitude { get; set; }
  10. }
  11. // 其他类的翻译...

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

  1. 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):

  1. public class Fact
  2. {
  3. public string fact { get; set; }
  4. public int length { get; set; }
  5. }

and you are deserializating the json to the object with:

  1. Fact fact = JsonConvert.DeserializeObject&lt;Fact&gt;(webRequest.downloadHandler.text);

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

  1. public class myNewClass
  2. {
  3. public List&lt;Result&gt; results { get; set; }
  4. public Info info { get; set; }
  5. }
  6. public class Coordinates
  7. {
  8. public string latitude { get; set; }
  9. public string longitude { get; set; }
  10. }
  11. public class Dob
  12. {
  13. public DateTime date { get; set; }
  14. public int age { get; set; }
  15. }
  16. public class Id
  17. {
  18. public string name { get; set; }
  19. public string value { get; set; }
  20. }
  21. public class Info
  22. {
  23. public string seed { get; set; }
  24. public int results { get; set; }
  25. public int page { get; set; }
  26. public string version { get; set; }
  27. }
  28. public class Location
  29. {
  30. public Street street { get; set; }
  31. public string city { get; set; }
  32. public string state { get; set; }
  33. public string country { get; set; }
  34. public int postcode { get; set; }
  35. public Coordinates coordinates { get; set; }
  36. public Timezone timezone { get; set; }
  37. }
  38. public class Login
  39. {
  40. public string uuid { get; set; }
  41. public string username { get; set; }
  42. public string password { get; set; }
  43. public string salt { get; set; }
  44. public string md5 { get; set; }
  45. public string sha1 { get; set; }
  46. public string sha256 { get; set; }
  47. }
  48. public class Name
  49. {
  50. public string title { get; set; }
  51. public string first { get; set; }
  52. public string last { get; set; }
  53. }
  54. public class Picture
  55. {
  56. public string large { get; set; }
  57. public string medium { get; set; }
  58. public string thumbnail { get; set; }
  59. }
  60. public class Registered
  61. {
  62. public DateTime date { get; set; }
  63. public int age { get; set; }
  64. }
  65. public class Result
  66. {
  67. public string gender { get; set; }
  68. public Name name { get; set; }
  69. public Location location { get; set; }
  70. public string email { get; set; }
  71. public Login login { get; set; }
  72. public Dob dob { get; set; }
  73. public Registered registered { get; set; }
  74. public string phone { get; set; }
  75. public string cell { get; set; }
  76. public Id id { get; set; }
  77. public Picture picture { get; set; }
  78. public string nat { get; set; }
  79. }
  80. public class Street
  81. {
  82. public int number { get; set; }
  83. public string name { get; set; }
  84. }
  85. public class Timezone
  86. {
  87. public string offset { get; set; }
  88. public string description { get; set; }
  89. }

and deserializate with:

  1. 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 字符串并反序列化一个名称属性:

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

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

  1. Name name = JObject.Parse(webRequest.downloadHandler.text)[&quot;results&quot;][0][&quot;name&quot;]
  2. .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:

确定