首页 > 解决方案 > 确保 GET/POST 请求上的 ObjectMapper 行为一致

问题描述

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

@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从字符串时间戳解析 s。例如,以下请求可以正常工作:

POST 的正文/store

{
  "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"]

看起来这个解析没有使用与ObjectMapperPOST 方法相同的方法。有没有办法解决这个问题?

标签: javaspringjackson

解决方案


似乎 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));
  }

}

然后我将此方法添加到控制器中:

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

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


推荐阅读