【问题标题】:How to properly parse string into integer inside JSONParser?如何在 JSONParser 中正确地将字符串解析为整数?
【发布时间】:2017-06-04 14:36:00
【问题描述】:

我有这个代码来检索我在数据库中的值:

            if(json != null){
            try{
                result = json.getJSONArray("monthly");
                if(!result.toString().equals("[]")) {
                    for (int i = 0; i < result.length(); i++) {
                        JSONObject source = result.getJSONObject(i);
                        String month = source.getString("month");
                        String counted = source.getString("counted");

                        Toast.makeText(getActivity(), month, Toast.LENGTH_SHORT).show();

                    }

注意

String month = source.getString("month");

返回 2 秒左右后才加载的值很快。但是当我尝试使用此代码将该值解析为整数时:

int 月 = Integer.parseInt(source.getString("month"));

需要很长时间才能完成。那么我要问的是如何正确地将数据解析为整数?

编辑: JSON

{"monthly":[{"month":"2","counted":"1"},{"month":"3","counted":"1"},{"month": "4","counted":"1"},{"month":"5","counted":"5"},{"month":"6","counted":"2"},{ "月":"7","计数":"3"},{"月":"8","计数":"1"},{"月":"9","计数":"2 "},{"month":"10","counted":"1"},{"month":"11","counted":"3"},{"month":"12","counted ":"2"}]}

【问题讨论】:

  • 除了 getInt 或 optInt 之外别无选择...阅读文档
  • 检查equals("[]") 是没有意义的,顺便说一句。您已经检查了数组长度

标签: android json parsing


【解决方案1】:

您可以在 JSONObject 上使用 getInt:

source.getInt("month") 

性能始终是一个问题,但在解析数据时,取决于大小可能会产生相当大的影响。如果您尝试在 UI 线程上执行此操作,则不应该这样做。而是使用一些后台线程。 AsyncTask 是 Android 在后台线程上运行代码然后将结果返回给 UI 线程的特定方式。

编辑:

这是我拥有的代码,使用 getString 与 getInt 没有显着的性能影响,因此您的代码中的其他地方一定存在问题。

    try {
        JSONObject json =
            new JSONObject("{'monthly':[{'month':'2','counted':'1'},{'month':'3','counted':'1'},{'month':'4','counted':'1'},{'month':'5','counted':'5'},{'month':'6','counted':'2'},{'month':'7','counted':'3'},{'month':'8','counted':'1'},{'month':'9','counted':'2'},{'month':'10','counted':'1'},{'month':'11','counted':'3'},{'month':'12','counted':'2'}]}");
        JSONArray result = json.getJSONArray("monthly");
        for (int i = 0; i < result.length(); i++) {
            JSONObject source = result.getJSONObject(i);
            int month = source.getInt("month");
            String counted = source.getString("counted");

            Toast.makeText(this,
                           "" + month,
                           Toast.LENGTH_SHORT)
                 .show();
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

【讨论】:

  • 我也尝试了 getInt 但也需要时间来加载。我不知道多久了,因为它还没有完成加载
  • 你应该也发布你的json。
  • 我只是想到你的 try catch 块可能掩盖了你遇到的真正问题。您是否在异常块中执行全部捕获而不是仅捕获 JSONException?如果您尝试使用 int 进行 Toast,您很可能会遇到 Resource Not Found 异常。
猜你喜欢
  • 2021-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多