简体   繁体   中英

Extract all values of a key from a JSON array and add them to List

I am trying to Extract all values of a key from a JSON array and add them to List.

@SuppressWarnings({ "null", "unchecked" })
    public static void main(String[] args) {
        @SuppressWarnings("rawtypes")
        java.util.List FResult = null;

        String str = "[{\"email_address\":\"Test@test.com\",\"user_id\":1001,\"user_name\":\"Ben\",\"employee_id\":1001},{\"email_address\":\"Test@test.com\",\"user_id\":1001,\"user_name\":\"Ben\",\"employee_id\":1001}]";
        JSONArray objects = new JSONArray(str);

        for(int i=0;i<objects.length();i++){
            JSONObject jsonObject = objects.getJSONObject(i);

            FResult.add(jsonObject.getInt("user_id"));

I am trying to extract all values of user_id and add them to a List.

java.util.List FResult = null;

You are getting a NullPointerException because your List is null . You need to initialize your List :

java.util.List<Integer> FResult = new ArrayList<>();

The fact is that you are calling a method from a null object so it throws a nullpointerexception.

List<int> FResult = new ArrayList<>();

I hope it will solve your issue.

Regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM