从Java中的JSONArray中获取一组整数



我有以下java代码,其中我试图从JSONArray对象中提取一组整数。我该怎么做?

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?

注意,addressIds字段的类型为:Set<Integer>

您可以尝试在流中将Object强制转换为Integer。

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

您可以尝试以下操作:

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

最新更新