Jackson Json Object mapper : how to map an array?

10,801

Well, if you are trying to deserialize json to an object of type UserListBean, then you need to deserialize a JSONObject (Java Objects tend to map to JSONObjects).

Therefore, your outer most json construct should be an object. Your outer most json construct is a JSONArray.

Your UserListBean has a single field, which is a List<UserBean>. So your top level json construct (which is a JSONObject) should contain a single field with the name 'userList' with a value that is a JSONArray (Java Collections tend to map to JSONArrays).

I think this is the actual json you are looking for:

{
  "userList":[
     {
       "id":1,
       "userName":"bob",
       "password":"403437d5c3f70b1329f37a9ecce02adbbf3e986"
     }
  ]
}

If you have no control over the json coming in, then you probably want to ditch the parent object UserListBean and deal directly with the List<UserBean>, as that would work with the json you have provided.

Share:
10,801
kaffein
Author by

kaffein

Updated on June 04, 2022

Comments

  • kaffein
    kaffein almost 2 years

    I am trying to map an array from a backend api call. How can I map this data knowing that :

    the following classes will be used to hold the json array data :

        @Data
        private static class UserListBean {
            private List<UserBean> userList;
        }
    
        @Data
        private static class UserBean {
            private String id;
            private String userName;
            private String password;
        }
    

    the json will have the following format (the following example just have one item in it) :

    [
       {
          "id":1,
          "userName":"bob",
          "password":"403437d5c3f70b1329f37a9ecce02adbbf3e986"
       }
    ]
    

    I am using Jackson and I have tried the following so far but it keeps sending me back an exception

            final ObjectMapper mapper = new ObjectMapper();
            mapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            final ObjectReader reader = mapper.reader(UserListBean.class);
            GeoHubAccountListBean accounts = null;
    
            try {
                accounts = reader.readValue(jsonString);
            } catch (final IOException ex) {
                log.error("Cannot convert JSON into a list of users", ex);
            }
    

    Here the final ObjectReader reader = mapper.reader(UserListBean.class); throws an exception

    Can not deserialize instance of com.xxx.XXX$UserListBean out of START_ARRAY token
    

    Any idea ?

    thanks