0

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?

4

1 回答 1

0

我认为您应该将 UserInfo 设为静态。Jackson 无法构造 UserInfo 类。

我尝试了这种改变,它对我有用:

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;
    }
}

和 :

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);
    }
}
于 2017-04-03T12:34:37.283 回答