java - 如何将请求正文作为 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"
}
那可能吗?
解决方案
推荐阅读
- asp.net-core-mvc - 如何在 .NET Core 5 MVC 中使用使用 RouteOptions?(强制小写 URL 等)
- python - 将日期时间字符串解析为日期时间对象而不设置格式
- sql - Visual Studio mvc 一键更新多个数据
- c++ - 演示一个打印字符串组合的类
- qt - 在 WebEngineView 中禁用 qml 的上下文菜单
- python - Python:使用 Numpy 删除“for”循环
- sorting - 按字符串的最后一个字符对压缩列表(字符串,'Line2D' 的实例)进行排序
- typescript - 为什么需要虚拟属性才能使类型保护起作用?
- python - 基于不同值掩码的数组求和
- r - 将国家分为热带与非热带 R