将嵌套对象发送到 Spring POST

我有 Angular 发送的 JSON 字符串:


{

   "transaction_id": "1234",

   "usage": "Test Usage",

   "billing_address": {

      "first_name": "name",

      "last_name": "name",

      "address1": "street 1234",

      "zip_code": "11923"

   },

   "shipping_address": {

      "first_name": "name",

      "last_name": "name",

      "address1": "street 1234",

      "zip_code": "11923"

   }  

}

Java代码:


public class DTO {


    private String transaction_id;

    private String usage;

    private BillingAddress billingAddress;

    private ShippingAddress shippingAddress;


    ... getter/setter

}


public class BillingAddress {


    private String firstName;

    private String lastName;

    private String address1;    

    private String zip_code;

    ... getter/setter

}


public class ShippingAddress {


    private String firstName;

    private String lastName;

    private String address1;    

    private String zip_code;

    ... getter/setter

}

弹簧端点:


@PostMapping(value = "/{id}", consumes = { MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_JSON_VALUE })

      public ResponseEntity<?> handleWpfMessage(@PathVariable("id") id,

              @RequestBody DTO data){

        ....

}

映射内部对象billing_address以及shipping_address正确映射值的正确方法是什么?我是否需要添加注释才能正确映射它们?


繁花不似锦
浏览 124回答 3
3回答

慕沐林林

您应该将以下注释添加到 DTO 类中:public class DTO {&nbsp; &nbsp; private String transaction_id;&nbsp; &nbsp; private String usage;&nbsp; &nbsp; @JsonProperty("billing_address")&nbsp; &nbsp; private BillingAddress billingAddress;&nbsp; &nbsp; @JsonProperty("shipping_address")&nbsp; &nbsp; private ShippingAddress shippingAddress;&nbsp; &nbsp; ... getter/setter}

哆啦的时光机

您的角度客户端使用蛇盒。为了使 jackson 正确反序列化,您可以使用以下命令进行全局配置:spring.jackson.property-naming-strategy=SNAKE_CASE但是您也可以为特定的类配置它:@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class) public&nbsp;class&nbsp;DTO&nbsp;{ }

撒科打诨

正如已经提到的,您可以在类中使用 Jackson 属性映射注释DTO。@JsonProperty("billing_address") private&nbsp;BillingAddress&nbsp;billingAddress;这意味着,在 json 中,属性billing_address将被分配给billingAddress变量。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java