java - 确保 GET/POST 请求上的 ObjectMapper 行为一致

标签 java spring jackson

我有一个类似于以下的方法,该方法已经存在并且工作正常:

@PostMapping(
      value = "/store",
      consumes = "application/json")
public ResponseEntity<String> postConversionEvent(@RequestBody Event event) {
  ...
}

现在还需要通过 GET 方法发布信息,如下所示:

@GetMapping("/store")
public ResponseEntity<String> postConversionEventAsGet(Event event) {
  ...
}

出于所有意图和目的,我们可以假设 Event 类看起来包含单个 org.joda.time.DateTime 字段。为了支持这一点,我有一个自定义的ObjectMapper,它支持从字符串时间戳解析DateTime。例如以下请求可以正常工作:

发送到 /store 的 POST 正文:

{
  "date": "238572349834"
}

但是,当我将其作为 GET 发送时,例如:

https://someUrl.com/store?date=238572349834

我收到以下错误:

Field error in object 'event' on field 'date': rejected value [238572349834]; codes [typeMismatch.Event.date,typeMismatch.date,typeMismatch.org.joda.time.DateTime,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [Event.date,date]; arguments []; default message [date]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'org.joda.time.DateTime' for property 'date'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [org.joda.time.DateTime] for value '238572349834'; nested exception is java.lang.IllegalArgumentException: Invalid format: "238572349834" is malformed at "8572349834"]

看起来此解析没有使用与 POST 方法相同的 ObjectMapper。有什么办法可以解决这个问题吗?

最佳答案

看起来 GET 请求不是使用 ObjectMapper 序列化的,而是使用 WebDataBinder 进行映射的。

该类已创建:

public class DateTimeFromTimestampEditor extends PropertyEditorSupport {

  @Override
  public String getAsText() {
    return Long.toString(((DateTime) getValue()).getMillis());
  }

  @Override
  public void setAsText(String text) throws IllegalArgumentException {
    setValue(new DateTime(Long.parseLong(text), DateTimeZone.UTC));
  }

}

然后我将此方法添加到 Controller 中:

@InitBinder
public void dataBinding(WebDataBinder binder) {
  binder.registerCustomEditor(DateTime.class, new DateTimeFromTimestampEditor());
}

之前失败的 GET 请求 (https://someUrl.com/store?date=238572349834) 现在可以成功反序列化。

关于java - 确保 GET/POST 请求上的 ObjectMapper 行为一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58119846/

相关文章:

java - MediaRecorder 在 android 上开始视频捕捉的问题

java - 使用 Google Cloud Dataflow 从 Outlook 下载附件并将其存储在 Google Cloud Storage 中

java - 什么是默认的 Spring Boot 应用程序上下文?

java - 将 spring-boot 1.5 迁移到 2.0 后,Webservices 调用出现 405 错误

jackson - 作为 JSON 列表的集合包装?

java - 将具有多个条目的 JSON 映射到数组

java - 为什么 org.w3c.dom 解析我的 xml 是错误的?

java - 同步块(synchronized block)未在 servlet 中执行

java - spring-hibernate映射问题

java - 使用自定义查询进行 JPA 优化