我有一个类似于以下的方法,该方法已经存在并且工作正常:
@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/