首页 > 解决方案 > 如何将请求正文作为 JSON 完全发送到我的 API?

问题描述

我正在将 Spring Boot 与 Jackson 一起使用,并且正在处理事务日志记录。我正在尝试完全按照发送的方式捕获发送给我的请求正文。我将对象转换为 JSON 的方式如下:

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

@Autowired
private Jackson2ObjectMapperBuilder objectMapperBuilder;
// I have a Bean for my Jackson config in the application setup class 
// and am using this class to ensure consistency between my logs and the output

public String objectToJson(){

     ObjectMapper mapper = objectMapperBuilder.build();
     return mapper.writeValueAsString(requestBody);
}

这在大多数情况下都有效。这只是我使用 JsonProperty 的类的问题,例如:

import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;

public class UserDTO {

     // Input Fields

     @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
     private String username;

     @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
     private String password;


      // Output Fields

      @ApiModelProperty(hidden = true)
      @JsonProperty(access = JsonProperty.Access.READ_ONLY)
      private LocalDateTime createdDate;

      @ApiModelProperty(hidden = true)
      @JsonProperty(access = JsonProperty.Access.READ_ONLY)
      private LocalDateTime updatedDate;
 }

问题是它完全按照它的配置去做。我需要在使用我指定的写入修饰符时将对象请求正文转换为 JSON 格式,因为这就是它进入我的代码的方式。

无论如何我可以反转映射逻辑来满足这个要求吗?

 // @RequestBody -> Mapper Convert (Using Write Rules) -> String JSON

试图澄清

当如上所述在UserDTO类型的 @RequestBody 上使用上述 objectToJson 方法,我看到的输出如下:

 {
 "createdDate": "2018-11-06 00:00:00",
 "updatedDate": "2018-11-06 00:00:00"
 }

当我希望输出包含整个对象时,包括 WRITE_ONLY 字段,例如:

 {
 "username": "myUserName9",
 "password": "securepassword123",
 "createdDate": "2018-11-06 00:00:00",
 "updatedDate": "2018-11-06 00:00:00"
 }

那可能吗?

标签: javajackson

解决方案


推荐阅读