Spring Boot API 的 Controller 如何获得发送的 JSON 数据

HoneyMoose
4 min readJan 26, 2021

--

我们知道可以发送 JSON 数据到 API 上面。

通常我们都会使用 POST 方法,在实际编程的时候我们应该如何获得发送的 JSON 数据呢?

Controller 获得 JSON 数据

在客户端通过 API 发送 JSON 数据到 Controller 的时候,我们可以在 Controller 使用 RequestBody 注解来获得 JSON 数据。

考察下面的代码:

/**
* Search Question Index
*
* @return
*/
@PostMapping("/sold")
public ResponseEntity<?> searchUser(@RequestBody RealEstateRequest realEstateRequest) {
logger.debug("realEstateRequest - {}" , realEstateRequest.getPropertyTown()); REListing reListing= listingService.getREListingById(); return new ResponseEntity<REListing>(reListing, HttpStatus.OK);
}

在 API 获得 JSON 数据后,将会尝试将 JSON 数据的内容设置到对象 RealEstateRequest 中。

所以,我们还需要在代码中定义一个对象 RealEstateRequest。

RealEstateRequest 对象的代码如下,在下面的代码中,我们省下了上面需要导入的 package 等

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;
}
}

在这里需要注意的是,为了能够设置正确的值到对象中,你 propertyTown 的这个变量需要和 JSON 对象中的变量相同。

所以你的 JSON 测试数据应该为:

{    "propertyTown" : "Manchester"}

通过 API 查看对象,你会看到从客户端传递的 JSON 数据已经被设置为正常的数据了。

POSTMAN 从客户端发送的数据如下:

JSON 数据字段名

在上面的示例中,我们定义的一个 JSON 字段名为:propertyTown。

如果不做任何设置的话,你的对象是需要使用与这个字段名完全相同的名字才能获得需要的数据的,有时候我们可能不希望这样。我们希望使用不同的名字,例如我们希望设置字段名为:property_town,但是我们还是希望 propertyTown 变量能够获得值。

这个时候你就需要使用:JsonProperty 注解了。

可以在定义的对象中使用 @JsonProperty(“property_town”) 注解。

原因是 RequestBody 使用 jackson 来映射对象的,所以 JsonProperty 这个是 jackson 的注解,主要告诉 jackson 来如何对字段中的数据来进行映射。

在完成上面的修改后,你的 JSON 数据应该是如下的:

然后再对 API 进行测试,你会看到 propertyTown 也能够设置上你传递的参数。

https://www.ossez.com/t/spring-boot-api-controller-json/13217

--

--

No responses yet