Search code examples
jackson2

How to use Jackson to deserialise list in java?


My Java Class is

public class User {

     private List<UserInfo> userInfoList;

     public class UserInfo {
         private String id;

     }
}

Let's assume it has getter, setter method.

json is

{"userInfoList" : [{"id":"a", "id":"b"}]}

I tried to deserialize it like below.

objectMapper.readValue(json, User.class);

But it throws error.

Can not construct instance of User$UserInfoList: no suitable constructor found

How to deserialize it?


Solution

  • I think you should make UserInfo static. Jackson cannot construct the UserInfo class.

    I tried with that change and it works for me :

    public class User {
    
        private List<UserInfo> userInfoList;
    
        public static class UserInfo {
            private String id;
    
            public UserInfo() {
                super();
            }
    
            public String getId() {
                return id;
            }
    
            public void setId(String id) {
                this.id = id;
            }
        }
    
        public List<UserInfo> getUserInfoList() {
            return userInfoList;
        }
    
        public void setUserInfoList(List<UserInfo> userInfoList) {
            this.userInfoList = userInfoList;
        }
    }
    

    And :

    public class App {
        public static void main(String[] args) throws IOException {
            ObjectMapper mapper = new ObjectMapper();
    
            User.UserInfo ui1 = new User.UserInfo();
            ui1.setId("a");
    
            User.UserInfo ui2 = new User.UserInfo();
            ui2.setId("b");
    
            List<User.UserInfo> userInfoList = new ArrayList<User.UserInfo>();
            userInfoList.add(ui1);
            userInfoList.add(ui2);
    
            User user = new User();
            user.setUserInfoList(userInfoList);
    
            System.out.println(mapper.writeValueAsString(user));
    
            user = mapper.readValue(mapper.writeValueAsString(user), User.class);
        }
    }