Home > Software design >  Getting set of Integers from a JSONArray in Java?
Getting set of Integers from a JSONArray in Java?

Time:12-22

I have the following java code where I am trying to pull a set of integers from a JSONArray object. How can I do so?

JSONObject actionDetail = new JSONObject("myJsonOject");

int personId = actionDetail.getInt("personId");
JSONArray addressIds = actionDetail.getJSONArray("addressIds");

Action action = new Action();

action.setPersonId(personId); //working ok

action.setAddressIds(): //todo - how to get list of ints from the JsonArray?

Note that the type of addressIds field is: Set<Integer>

CodePudding user response:

You can try something like :

Set<Integer> result = IntStream.range(0, addressIds.length())
        .mapToObj(addressIds::get)
        .map(Integer::valueOf)
        .collect(Collectors.toSet());

CodePudding user response:

You can try cast Object to Integer in stream.

action.setAddressIds(addressIds.toList().stream().map(k -> (Integer) k).collect(Collectors.toSet()));
  • Related