在 Spring 中将嵌套类序列化为表行

我正在使用具有预期依赖项(Jackson、Hibernate 等)的 Spring Boot。


我有一个名为 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。有没有我可以用来告诉杰克逊如何正确解析的注释?


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;

}

}


qq_花开花谢_0
浏览 129回答 1
1回答

慕无忌1623718

错误消息说 Jackson 不知道如何创建 type 的对象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}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java