【问题标题】:Accessing data inside JSON Array with C#使用 C# 访问 JSON 数组中的数据
【发布时间】:2020-07-09 12:40:36
【问题描述】:

我正在统一编写一个 C# 脚本来获取玩家所在位置的天气。 我几乎完成了,我所要做的就是从天气 API 返回的 JSON 文件中提取数据。我正在使用 SimpleJSON 来读取和提取 JSON。 JSON 看起来像这样:

{
  "coord": {
    "lon": (floating point number),
    "lat": (floating point number)
  },
  "weather": [
    {
      "id": 804,
      "main": "Clouds",
      "description": "overcast clouds",
      "icon": "04n"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 292.01,
    "feels_like": 292.12,
    "temp_min": 291.15,
    "temp_max": 293.15,
    "pressure": 1018,
    "humidity": 72
  },
  "visibility": 9000,
  "wind": {
    "speed": 1.5,
    "deg": 130
  },
  "clouds": {
    "all": 100
  },
  "dt": 1594239812,
  "sys": {
    "type": 1,
    "id": 1308,
    "country": "COUNTRY-CODE",
    "sunrise": 1594178675,
    "sunset": 1594235893
  },
  "timezone": 7200,
  "id": 2954172,
  "name": "CITY",
  "cod": 200
}

我需要访问“天气”数组中的“描述”。但是我不知道如何让它工作。 这是我的 C# 代码:

var PARSED_JSON_2 = JSON.Parse(JSON_DATA_2);
var weather_description = PARSED_JSON_2["weather"][2]; //returns null
//I also tried something like this:
var weather_description = PARSED_JSON_2["weather"]["description"][2]; //returns null
var weather_description = PARSED_JSON_2["weather"]["description"][2].Value; //Returns nothing.

Debug.Log 会显示一个空字符串。

我尝试在此处遵循此参考:http://wiki.unity3d.com/index.php/SimpleJSON

(简而言之,我需要访问 JSON 数组中的一个元素,但我不知道如何访问。感谢任何帮助。)

【问题讨论】:

  • 需要用 SimpleJSON 来完成吗?或者您可以使用任何其他第三方库吗?
  • 我在 linux 上,所以我的选择并不丰富。到目前为止,我发现 SimpleJSON 效果最好,但是如果您有建议,我也会尝试一下。只要我能弄清楚如何访问json文件的“天气”数组中的元素“描述”。
  • 您可以创建 C# 类并将其反序列化为 C# 对象。您可以根据需要更新字段
  • 我会建议使用Newtonsoft(我不知道它是否适用于Linux),或者你可以使用我的JsonManager(github.com/EricBatlle/SimpleUnityUtils/tree/master/Assets/…)
  • @Lotan 它是跨平台的/它是否与统一工作?我的目标是制作这个跨平台,主要针对移动设备。哦,大声笑。我收回了 - 刚刚看到使用 UnityEngine;

标签: c# arrays json unity3d


【解决方案1】:

您正在尝试访问不存在的索引2。 weather 数组中只有 一个 元素。在这种情况下,SimpleJSON 库只是返回 null 而不是抛出适当的异常!

你应该使用索引0

var weather_description = PARSED_JSON_2["weather"][0];

通常,您还可以使用JsonUtility 并将您的完整数组反序列化为适当的 c# 类表示形式。然后你会立即看到数组有多少元素,或者正确地得到预期的异常。

你的看起来像

[Serializable]
public class Root
{
    public Coord coord;
    public Weather[] weather;
    public string @base;
    public Main main;
    public int visibility;
    public Wind wind;
    public Clouds clouds;
    public double dt;
    public Sys sys;
    public int timezone;
    public int id;
    public string name;
    public int cod;
}

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

[Serializable]
public class Weather
{
    public int id;
    public string main;
    public string description;
    public string icon;
}

[Serializable]
public class Main
{
    public float temp;
    public float feels_like;
    public float temp_min;
    public float temp_max;
    public float pressure;
    public float humidity;
}

[Serializable]
public class Wind
{
    public float speed;
    public float deg;
}

[Serializable]
public class Clouds
{
    public int all;
}

[Serializable]
public class Sys
{
    public int type;
    public int id;
    public string country;
    public int sunrise;
    public int sunset;
}

然后你会做例如

var root = JsonUtility.FromJson<Root>(JSON_DATA_2);
var weather = root.weather[0];

这种方法的最大优势在于,您还可以通过写入 a 直接在 Inspector of Unity 中查看结果

public class JsonTester : MonoBehaviour
{
    [Header("Input")]
    [Tooltip("Copy your json string here and call \"Test\" from the Context menu")]
    [SerializeField] [TextArea] private string _testJson;

    [Header("Output")]
    [SerializeField] private Root _receivedJson;

    [ContextMenu(nameof(Test))]
    private void Test()
    {
        VisualizeJson(_testJson);
    }

    public void VisualizeJson(string json)
        JsonUtility.FromJsonOverwrite(json, _receivedJson);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    • 2011-08-02
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多