本文共 1979 字,大约阅读时间需要 6 分钟。
在开发过程中,我们经常需要将 JSON 数据发送到 API 上。通常,我们会使用 POST 方法来发送 JSON 数据,但在实际编程中,如何获取这些 JSON 数据并将其映射到对象中是关键。
在 Spring Boot 应用中,我们可以通过在 Controller 方法参数上注解 @RequestBody 来接收 JSON 数据。这个注解会自动将请求体中的 JSON 内容解析到方法参数中。
例如,以下是一个简单的 Controller 方法:
@PostMapping("/sold")public ResponseEntity searchUser(@RequestBody RealEstateRequest realEstateRequest) { logger.debug("realEstateRequest - {}" , realEstateRequest.getPropertyTown()); REListing reListing = listingService.getREListingById(); return new ResponseEntity<>(reListing, HttpStatus.OK);} 为了确保 JSON 数据能够正确映射到对象中,我们需要确保对象的字段名与 JSON 数据中的字段名一致。例如,如果 JSON 数据为:
{ "propertyTown": "Manchester"} 则 RealEstateRequest 对象的字段名也应该是 propertyTown。
public class RealEstateRequest implements Serializable { private static final long serialVersionUID = 6474765081240948885L; private String propertyTown; public String getPropertyTown() { return propertyTown; } public void setPropertyTown(String propertyTown) { this.propertyTown = propertyTown; }} 在某些情况下,JSON 数据的字段名可能与对象的字段名不一致。例如,假设 JSON 数据使用 property_town 作为字段名,而我们的对象字段名是 propertyTown。
为了解决这个问题,我们可以使用 @JsonProperty 注解,它告诉 Jackson 将 JSON 中的字段名映射到对象的相应字段中。
public class RealEstateRequest implements Serializable { private static final long serialVersionUID = 6474765081240948885L; private String propertyTown; @JsonProperty("property_town") public String getPropertyTown() { return propertyTown; } public void setPropertyTown(String propertyTown) { this.propertyTown = propertyTown; }} 这样,JSON 数据中的 property_town 会自动映射到 propertyTown 字段中。
通过 Postman 或其他 REST 客户端工具,我们可以发送以下 JSON 数据:
{ "property_town": "Manchester"} 发送请求后,检查 Controller 方法中的 realEstateRequest 对象,应能够正确获取到 propertyTown 字段的值。
通过使用 @RequestBody 注解,我们可以轻松地将客户端发送的 JSON 数据映射到对象中。在字段名不一致的情况下,@JsonProperty 注解可以帮助我们实现数据的正确映射。通过合理配置和测试,我们可以确保 JSON 数据能够正确地被接收和处理。
转载地址:http://prld.baihongyu.com/