【问题标题】:How to get a certain elements inside an array inside a jsonObject如何在jsonObject中的数组中获取某些元素
【发布时间】:2019-03-28 01:38:59
【问题描述】:

我正在使用 JSON 在 java 中导出一些数据,然后我正在读取该数据并尝试从 JSON 对象内的数组中获取元素,但我遇到了问题。

我已经尝试了很多类似的东西

jsonObject.get("InGameCord").get("x")
Object Testo = jsonObject.get("InGameCord");
Testo.x

类似的东西以及更多不起作用的东西,所以删除了代码。

这是导出的 JSON 文件,我正在尝试访问 InGameCord 数组 X 或 Y。

{"BaseID":1,"BaseName":"Bandar-e-Jask Airbase","InGameCord":[{"x":463,"y":451}]}

这是我的文件阅读器代码

FileReader reader = new FileReader(filename);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
System.out.println(jsonObject);
System.out.println("BaseName: "+jsonObject.get("BaseName"));
System.out.println("BaseID: "+jsonObject.get("BaseID"));
System.out.println("InGameCord: "+jsonObject.get("InGameCord"));

所有这些都有效并导出正确的信息。

所以我试图让我们说出 InGameCord 的 X 值。

int X = 463;

【问题讨论】:

  • 您从哪里获得 JSONObject 和 JSONParser?我问是因为 Java EE 8 规范对接口名称使用不同的大小写:javax.json.JsonObjectjavax.json.stream.JsonParser
  • import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser;

标签: java arrays netbeans filereader json-simple


【解决方案1】:

鉴于您的 JSON 数据{"BaseID":1,"BaseName":"Bandar-e-Jask Airbase","InGameCord":[{"x":463,"y":451}]}

  • "InGameCord" 是可以实例化为JSONArray 的数组的名称。
  • 该数组仅包含一个元素:{"x":463,"y":451}
  • 该数组元素可以实例化为JSONObject。它包含两个名称/值对:

    • "x",值为 463。
    • "y" 的值为 451。

所以根据你提供的代码,实例化JSONArray

JSONArray numbers = (JSONArray) jsonObject.get("InGameCord");

将数组的第一个(也是唯一一个)元素检索到JSONObject

JSONObject jObj = (JSONObject) numbers.get(0);

要将“x”的值转换为int 变量,将get() 返回的Object 转换为Number,然后获取它的intValue()

int value = ((Number) jObj.get("x")).intValue();

你甚至可以在一行中完成所有事情,但它很丑:

int y = ((Number) ((JSONObject) numbers.get(0)).get("y")).intValue();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-22
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    • 2021-03-22
    • 2021-07-08
    相关资源
    最近更新 更多