我正在将Spring Boot与预期的依赖项(Jackson,Hibernate等)一起使用。
我有一个名为Buildings的表,其中Unit,Number,Street等都是列。但是我更喜欢解析它,并将其作为我创建的名为“ StreetAddress”的类返回。
发送此JSON时,出现错误。
"address": {
"unit":"0101",
"number":"19",
"suffix":"STREET",
"suburb":"Example",
"state":"EXP",
"streetName":"Example",
"postCode":"400"
}
这是错误:
Cannot construct instance of `com.App.Entity.Helpers.StreetAddress` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
我在建筑模型中将其作为setAddress。有什么注释可以告诉Jackson如何正确解析吗?
private String subunit;
private Integer number;
private String streetname;
private String suffix;
private String suburb;
private String state;
private Integer postcode;
public void setAddress(StreetAddress address) {
this.subunit = address.getUnit();
this.number = address.getNumber();
this.streetname = address.getStreetName();
this.suffix = address.getSuffix().toString();
this.suburb = address.getSuburb();
this.state = address.getState().toString();
this.postcode = address.getPostCode();
}
说明:
public class StreetAddress {
private String unit;
private Integer number;
private String streetname;
private StreetSuffix suffix;
private String suburb;
private AUState state;
private Integer postcode;
public StreetAddress(String unit, int number, String street, StreetSuffix suffix, String suburb, AUState state, int postcode) {
this.unit = unit;
this.number = number;
this.streetname = street;
this.suffix = suffix;
this.suburb = suburb;
this.state = state;
this.postcode = postcode;
}
public String getUnit() {
return unit;
}
public Integer getNumber() {
return number;
}
public String getStreetName() {
return streetname;
}
public String getSuffix() {
return suffix.toString();
}
public String getSuburb() {
return suburb;
}
public AUState getState() {
return state;
}
public Integer getPostCode() {
return postcode;
}
}
答案 0 :(得分:1)
该错误消息指出,杰克逊不知道如何创建StreetAddress
类型的对象,因为找不到合适的构造函数。 Jackson期望使用无参数的构造函数(在这种情况下,它将通过分配字段或调用setter来传递JSON数据),或者期望带有注释的构造函数,该注释告诉Jackson应该将哪个JSON属性传递给哪个参数。
解决此问题的最简单方法是不声明构造函数,而是将字段设为公开字段:
public class StreetAddress {
public String unit;
// ... more fields here
}
或者,您可以将字段设为私有,但为每个字段声明一个setter:
public class StreetAddress {
private String unit;
// ... more fields here
public void setUnit(String unit) {
this.unit = unit;
}
// ... more setters here
}