我正在尝试使用Jackson序列化一个包含两个字符串和字符串映射到字符串的类。这是我试图序列化的json。我想知道是否存在问题,因为我正在尝试序列化空数组。
{
"filters": {
"test": [
"hi"
],
"groups": [],
"groupsOT": [],
"chains": [],
"chainsOT": [],
"locations": [],
"locationsOT": [],
"reports": [],
"reportsOT": []
},
"fromDate": "09.03.2015",
"toDate": "16.03.2015"
}
以下是用于尝试和序列化此类的类。
public class FilterRequest{
public String getToDate() {
return toDate;
}
public void setToDate(String toDate) {
this.toDate = toDate;
}
public String getFromDate() {
return fromDate;
}
public void setFromDate(String fromDate) {
this.fromDate = fromDate;
}
public Map<String, String[]> getFilters() {
return filters;
}
public void setFilters(Map<String, String[]> filters) {
this.filters = filters;
}
private String toDate;
private String fromDate;
private Map<String,String[]> filters;
public FilterRequest(){
filters = new HashMap<String,String[]>();
}
}
失败的代码只是
ObjectMapper mapper = new ObjectMapper();
FilterRequest requestParams = mapper.readValue(requestBody, FilterRequest.class);
我得到的错误是
No suitable constructor found for type [simple type, class com.aramburu.overall.web.controller.FilterController$FilterRequest]: can not instantiate from JSON object (need to add/enable type information?)
at [Source: {"filters":{"test":["hi"],"groups":[],"groupsOT":[],"chains":[],"chainsOT":[],"locations":[],"locationsOT":[],"reports":[],"reportsOT":[]},"fromDate":"09.03.2015","toDate":"16.03.2015"}; line: 1, column: 2]
答案 0 :(得分:1)
输出:
No suitable constructor found for type [simple type, class com.aramburu.overall.web.controller.FilterController$FilterRequest
表示FilterRequest
是一个内部类。
让FilterRequest
类保持静态(或者 - 更好的是 - 将其移出FilterController
)。
否则杰克逊无法实例化它(它需要父类的外部实例才能构造内部实例)。
答案 1 :(得分:0)
如果您的类被声明为内部类,则需要将其设置为静态。例如:
public class Application {
private static final String requestBody = "{\"filters\": {\"test\": [\"hi\"],\"groups\": [],\"groupsOT\": [],\"chains\": [],\"chainsOT\": [],\"locations\": [],\"locationsOT\": [],\"reports\": [],\"reportsOT\": []},\"fromDate\": \"09.03.2015\",\"toDate\": \"16.03.2015\"}";
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
FilterRequest requestParams = mapper.readValue(requestBody, FilterRequest.class);
System.out.println(requestParams);
}
public static class FilterRequest{
public String getToDate() {
return toDate;
}
public void setToDate(String toDate) {
this.toDate = toDate;
}
public String getFromDate() {
return fromDate;
}
public void setFromDate(String fromDate) {
this.fromDate = fromDate;
}
public Map<String, String[]> getFilters() {
return filters;
}
public void setFilters(Map<String, String[]> filters) {
this.filters = filters;
}
private String toDate;
private String fromDate;
private Map<String,String[]> filters;
public FilterRequest(){
filters = new HashMap<String,String[]>();
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.DEFAULT_STYLE);
}
}
}
此致