我的Java类是
public class User {
private List<UserInfo> userInfoList;
public class UserInfo {
private String id;
}
}
让我们假设它有getter,setter方法。
json是
{"userInfoList" : [{"id":"a", "id":"b"}]}
我试着像下面那样反序列化。
objectMapper.readValue(json, User.class);
但它会引发错误。
Can not construct instance of User$UserInfoList: no suitable constructor found
如何反序列化?
答案 0 :(得分:0)
我认为你应该使UserInfo保持静态。杰克逊无法构建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);
}
}