I am using springboot app and I want to map request body User having fields billingAddress and shippingAddress. I have define single Address class given below. Request body is given below. How would I define mapper so that request body can be easily transform? I don't want to define separate billingAddress and shippingAddress class.
Json Request:
{
"data": {
"billing_information": {
"billing_first_name": "John",
"billing_last_name": "Doe",
"billing_address_line1": "1295 Charleston Road",
"billing_address_line2": "Apt 1",
"billing_city": "Mountain View",
"billing_province": "CA",
"billing_postal_code": "94043",
"billing_country": "US"
},
"shipping_information": {
"shipping_first_name": "John",
"shipping_last_name": "Doe",
"shipping_address_line1": "1295 Charleston Road",
"shipping_address_line2": "Apt 1",
"shipping_city": "Mountain View",
"shipping_province": "CA",
"shipping_country": "US",
"shipping_postal_code": "94043"
}
}
}
Address.java:
public class Address {
private String firstName;
private String lastName;
private String addressLne1;
private String addressLne2;
private String city;
private String province;
private String postalCode;
private String country;
}
User.java:
public class User {
private Address billingAddress;
private Address shippingAddress;
}
Controller.java:
@RestController
public class Controller {
@PostMapping("/user")
public String user(@RequestBody User request) {
return "success";
}
}
First, the root node of a JSON has a property 'data', you can map using @JsonTypeName
, other alternative is to create a wrapper class and map it using @JsonProperty
to a mapper field
Then you can map the billing address and shipping address using @JsonProperty
annotation
@JsonTypeName("data")
@JsonTypeInfo(include= JsonTypeInfo.As.WRAPPER_OBJECT,use= JsonTypeInfo.Id.NAME)
class User {
@JsonProperty("billing_information")
private Address billingAddress;
@JsonProperty("shipping_information")
private Address shippingAddress;
// getters and setters
}
And finally, as Address
model fields need to be mapped to 2 different JSON properties, we can use @JsonAlias
to set an alias.
class Address {
@JsonProperty("billing_first_name")
@JsonAlias({"shipping_first_name"})
private String firstName;
@JsonProperty("billing_last_name")
@JsonAlias({"shipping_last_name"})
private String lastName;
@JsonProperty("billing_address_line1")
@JsonAlias({"shipping_address_line1"})
private String addressLne1;
...
// getters and setters
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.