【问题标题】:Getting Int values from JSON Android从 JSON Android 获取 Int 值
【发布时间】:2021-07-30 23:01:00
【问题描述】:

我得到一个这样的字符串值:

[{
  "data": [127, 145, 225, 167, 200, 173, 411, 505, 457, 243, 226, 156, 298, 237, 425, 405, 391, 258]
}]

现在我只想获取值,而不是键(“数据”)。我怎样才能做到这一点。喜欢:

[127, 145, 225, 167, 200, 173, 411, 505, 457, 243, 226, 156, 298, 237, 425, 405, 391, 258]

我试过了,但它调用了整个字符串:

try {
  final JSONObject obj = new JSONObject(s);

  final JSONArray geodata = obj.getJSONArray("data");
  final JSONObject person = geodata.getJSONObject(0);
  Log.d("myListjson", String.valueOf(person.getString("data")));

} catch (JSONException e) {
  e.printStackTrace();
}

【问题讨论】:

标签: java android arrays json android-studio


【解决方案1】:

您访问元素的方式是错误的。您应该使用循环来访问 JSONArray 中的每个元素

这应该有效

String s = "[{\"data\":[127, 145, 225, 167, 200, 173, 411, 505, 457, 243, 226, 156, 298, 237, 425, 405, 391, 258]}]";
        try {
            final JSONObject obj = new JSONObject(s);
            final JSONArray geodata = obj.getJSONArray("data");
            for(int i=0; i < geodata.length(); i++){
                int number = (int) geodata.get(i);
                Log.d("Number", String.valueOf(number));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

【讨论】:

    【解决方案2】:

    您可以执行以下操作:

        String json = "[{\"data\":[127, 145, 225, 167, 200, 173, 411, 505, 457, 243, 226, 156, 298, 237, 425, 405, 391, 258]}]";
    
        JSONArray jsonArray = new JSONArray(json).getJSONObject(0).getJSONArray("data");
    
        List<Integer> numbers = IntStream.range(0, jsonArray.length())
                .mapToObj(jsonArray::getInt)
                .collect(Collectors.toList());
    

    如果您遇到 Java 流问题,这里有一个替代方案:

        String json = "[{\"data\":[127, 145, 225, 167, 200, 173, 411, 505, 457, 243, 226, 156, 298, 237, 425, 405, 391, 258]}]";
    
        JSONArray jsonArray = new JSONArray(json).getJSONObject(0).getJSONArray("data");
    
        List<Integer> numbers = new ArrayList<>();
        int bound = jsonArray.length();
        for (int i = 0; i < bound; i++) {
            Integer anInt = (int)jsonArray.get(i);
            numbers.add(anInt);
        }
    

    输出:

    [127, 145, 225, 167, 200, 173, 411, 505, 457, 243, 226, 156, 298, 237, 425, 405, 391, 258]
    

    【讨论】:

    • 它在地图上抛出错误,错误:方法参考中抛出的类型 JSONException 不兼容
    • @HarshilPatel 这很奇怪,它对我有用。我现在将其更改为 mapToObj。您使用 Java 8 吗?
    • @HarshilPatel 我也添加了一个非 java-stream 方法
    猜你喜欢
    • 2016-08-20
    • 2014-08-02
    • 1970-01-01
    • 2013-05-18
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多