如何将JSON解析为int? [英] How do I parse JSON into an int?

查看:1717
本文介绍了如何将JSON解析为int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have Parsed some JSON data and its working fine as long as I store it in String variables.

我的问题是我需要int int varibable中的ID而不是在String中。
i试图进行投射 int id =(int)jsonObj.get();

My problem is that I need the ID in an int varibable and not in String. i have tried to make a cast int id = (int) jsonObj.get("");

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

But it gives an error message that I cannot convert an object to an int. So I tried to convert by using:

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

但这也无效。怎么了。 JSON如何使用int?
我的字符串工作得很好,只有当我尝试将它们作为int我才会遇到问题。

But also that is not working. What is wrong. How is JSON working with int? My strings are working just fine its only when I try to make them as an int I get problems.

这是我的代码:

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");

这篇关于如何将JSON解析为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆