有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从JSON Android获取Int值

我得到的字符串值如下:

[{
  "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();
}

共 (2) 个答案

  1. # 1 楼答案

    您可以执行以下操作:

        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]
    
  2. # 2 楼答案

    您访问元素的方式是错误的。您应该使用循环来访问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();
            }