【问题标题】:How to access single integer from JSONArray如何从 JSONArray 访问单个整数
【发布时间】:2020-02-06 12:57:11
【问题描述】:

我已将 jsonobject 转换为 jsonarray,其中包含用逗号分隔的这些数字 [12,20,26,25,89,92,30,16](示例数字) 如何单独访问每个数字并将其视为整数?

JSONObject JA = new JSONObject(data);
        for (int i = 0; i < JA.length(); i++) {
            try {
                JSONObject jobj1 = (JSONObject) JA.get("today");
                JSONObject jobj2 = jobj1.getJSONObject("Numbers");
                JSONArray jarray_list = jobj2.getJSONArray("list");

                Log.d(TAG, "Numbers = " + jarray_list);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

【问题讨论】:

  • 使用 split() 函数将字符串转换为单个数字的数组。然后使用 Integer.parseInt() 将它们转换为整数

标签: java android arrays json


【解决方案1】:

只需解析它。

String data = jarray_list.toString();
// omit [ & ]
data = data.substring(1, data.length() - 1);
String[] strNums = data.split(",");

for (String item : strNums) {
    int parsed = Integer.parseInt(item);

}

【讨论】:

    【解决方案2】:

    使用 split() 方法 -> 迭代器或简单的 for 循环来访问它们 -> Integer.parseInt(String s) 将它们解析/处理为 int

    【讨论】:

      猜你喜欢
      • 2016-03-14
      • 2015-06-24
      • 1970-01-01
      • 1970-01-01
      • 2013-10-23
      • 2013-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多