【问题标题】:JsonUtility.FromJson Cannot extract JSON data to stringJsonUtility.FromJson 无法将 JSON 数据提取到字符串
【发布时间】:2021-11-25 04:39:46
【问题描述】:

我正在尝试从本地主机后端的 REST API 返回的 JSON 结果中获取数据。我可以从名称字段中获取值,但无法获取坐标值。有什么办法吗?谢谢!

以下是我得到的结果。

{
    "coord" : {
        "lon" : xxx.xxx,
        "lat" : xx.xxxx
    },
    "weather" : [
        {
            "id" : 801,
            "main" : "Clouds",
            "description" : "few clouds",
            "icon" : "02d"
        }
    ],
    "base" : "stations",
    "main" : { 
        "temp":23.04,
        "feels_like":22.89,
        "temp_min":21.83,
        "temp_max":24.52,
        "pressure":916,
        "humidity":57
    },
    "name" : "Ma Nam Wat"
}

我的代码:

public class GetMethod : MonoBehaviour
{
    public WeatherInfo Info;
    void GetData() => StartCoroutine(GetData_Coroutine() );
    IEnumerator GetData_Coroutine()
    {
        string uri = "http://localhost:3000/api/weather/current?lat=22.426522&lon=114.234446&unit=metric";
        using (UnityWebRequest request = UnityWebRequest.Get(uri))
        {
            yield return request.SendWebRequest();
            if (request.isNetworkError || request.isHttpError)
                Debug.Log(request.error);
            else
                Debug.Log(request.downloadHandler.text);
            Info = JsonUtility.FromJson<WeatherInfo>(request.downloadHandler.text);
            Debug.Log(Info.coord.lon.ToString());
        }
    }

}
[SerializeField]
public class WeatherInfo
{
    public Coord coord;
    public string name;
}
[SerializeField]
public class Coord
{
    public float lon;
    public float lat;

}

【问题讨论】:

  • "基地" "名称" ??为什么没有在 WeatherInfo 中找到?它也在json中
  • 你的类应该有 System.Serializable 属性。

标签: json unity3d


【解决方案1】:

您将用于序列化非公共字段的属性[SerializeField] 与用于标记类型可序列化的[System.Serializable] 混淆了;)

[Serializable]
public class WeatherInfo
{
    public Coord coord;
    public string name;
}

[Serializable]
public class Coord
{
    public float lon;
    public float lat;
}

【讨论】:

    猜你喜欢
    • 2012-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    相关资源
    最近更新 更多