你好,我想知道如何在使用 spring boot 时将我的 json 消息映射到 java 中的对象。
假设我正在获取类似 json 的内容
{
"customerId": 2,
"firstName": "Jan",
"lastName": "Nowak",
"town": "Katowice"
}
我想在我的 java 程序中将其作为实体:
并且出于某种原因我不想匹配字段名称
public class Customer {
//Something like @Map("customerId")
private long OMG;
//Something like @Map("firstName")
private String WTF;
//Something like @Map("lastName")
private String LOL;
//Something like @Map("town")
private String YOLO;
我找不到应该使用的注解,不使用 jackson,只是内置了 spring boot 转换器??
Spring Boot 随 Jackson 开箱即用。
您可以使用 @RequestBody Spring MVC 注释将 json 字符串解码为 Java 对象...类似这样。
@RestController
public class CustomerController {
//@Autowired CustomerService customerService;
@RequestMapping(path="/customers", method= RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public Customer postCustomer(@RequestBody Customer customer){
//return customerService.createCustomer(customer);
}
}
使用带有相应 json 字段名称的 @JsonProperty 注释您的实体成员元素。
public class Customer {
@JsonProperty("customerId")
private long OMG;
@JsonProperty("firstName")
private String WTF;
@JsonProperty("lastName")
private String LOL;
@JsonProperty("town")
private String YOLO;
}