-2

I am getting a string value like this:

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

Now I just want to get values, and not the key ("data"). How can I do that. like :

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

I tried this but its calling whole string:

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();
}
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
  • Does this answer your question? [How to parse JSON in Java](https://stackoverflow.com/questions/2591098/how-to-parse-json-in-java) – a_local_nobody May 09 '21 at 08:47

2 Answers2

0

The way in which you are accessing the elements are wrong. You should use a loop to access each elements in the JSONArray

THIS SHOULD WORK

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();
        }
Sreehari K
  • 887
  • 6
  • 16
0

You can do the following:

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

Here's an alternative in case you are running into a problem with Java stream:

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

Output:

[127, 145, 225, 167, 200, 173, 411, 505, 457, 243, 226, 156, 298, 237, 425, 405, 391, 258]
Most Noble Rabbit
  • 2,728
  • 2
  • 6
  • 12