java - 确保 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"]
看起来这个解析没有使用与ObjectMapper
POST 方法相同的方法。有没有办法解决这个问题?
解决方案
似乎 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
) 现在可以成功反序列化。
推荐阅读
- java - 我的第一个代码问题!学习 Java 并需要帮助对数组执行基本统计信息
- atom-editor - Atom 功能键绑定。如何绑定 F5 将所选文本的大小写更改为大写
- linux - 为 mmap() 内存手动触发页面错误,用于长序列的随机读取
- javascript - How do I print out json data
- webots - 在 Webots 中编写机器人代码
- azure-devops - 您如何将 PBI 从一个 sprint 移动到另一个 sprint 并将其反映到 Rolling up 状态
- swift - 使用 Swift Enum 时,Objective-C 方法在 Swift 中不可见
- mysql - 如何检查sql表中列的所有条目是否为空?
- curve-fitting - 用于 msc ADAMS 软件中强加运动的样条拟合
- snowflake-cloud-data-platform - 对不同值求和