java - 如何将 JSON 解析为 int?

标签 java json

我已经解析了一些 JSON 数据,只要我将它存储在字符串变量中,它就可以正常工作。

我的问题是我需要一个 int 变量而不是 String 形式的 ID。 我已经尝试进行转换 int id = (int) jsonObj.get("");

但它给出了一条错误消息,指出我无法将对象转换为 int。 所以我尝试使用以下方法进行转换:

String id = (String) jsonObj.get("id");
int value = Integer.parseInt(id);

但这也行不通。怎么了。 JSON 如何与 int 一起工作? 我的字符串工作得很好,只有当我尝试将它们作为 int 时,我才会遇到问题。

这是我的代码:

public void parseJsonData() throws ParseException {

        JSONParser parser = new JSONParser();
        Object obj = parser.parse(jsonData);
        JSONObject topObject = (JSONObject) obj;
        JSONObject locationList = (JSONObject) topObject.get("LocationList");
        JSONArray array = (JSONArray) locationList.get("StopLocation");
        Iterator<JSONObject> iterator = array.iterator();

        while (iterator.hasNext()) {

            JSONObject jsonObj = (JSONObject) iterator.next();
            String name  =(String) jsonObj.get("name");
            String id = (String) jsonObj.get("id");
            Planner.getPlanner().setLocationName(name);
            Planner.getPlanner().setArrayID(id);


        }

    }

最佳答案

你可以使用 parseInt :

int id = Integer.parseInt(jsonObj.get("id"));

或者更好更直接的getInt方法:

int id = jsonObj.getInt("id");

关于java - 如何将 JSON 解析为 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15699953/

相关文章:

java - 类 unix 权限对象的类名

java - 从字符串设置所选项目 JComboBox

java - 如何在 web-inf/class 下的类命名空间中创建/写入文件

javascript - 如何解析 Google App Script 中的 JSON 响应?

python - SQLAlchemy中,dict更新方法如何与ORM交互?

json - 用于创建 EC2 的 AWS CloudFormation 模板 - 列出 IAM 角色

python - 将 ASCII 输出转换为 UTF-8

java stackoverflowerror 在无限循环中抛出

java - Spring Security 3.2 在用户之间分离数据

json - 使用jq合并多个JSON文件