为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

qq_花开花谢_0 2023-04-13 17:18:32
我正在使用具有预期依赖项(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;}}
查看完整描述

1 回答

?
慕无忌1623718

TA贡献1744条经验 获得超4个赞

错误消息说 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

}


查看完整回答
反对 回复 2023-04-13
  • 1 回答
  • 0 关注
  • 134 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信