前提
ajaxでGETリクエストを受信し、パラメータとしてJSONから日時を取得するAPIを作成しています。
日時のパラメータは、アノテーション@DateTimeFormatでバリデーションを行います。
実現したいこと
入力パラメータとして、JsonRequestクラスのdateフィールドに、"yyyy-MM-dd HH:mm:ss.SSS"形式の日時文字列をマッピングします。
発生している問題・エラーメッセージ
入力値で「2022-07-16 21:00:00.111」のように半角スペースを含む値を指定した場合に、マッピングに失敗します。エラーメッセージは、スタックトレースの抜粋です。
半角スペースをパターンに含めることはできないのでしょうか?
Caused by: com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.util.Date` from String "2022-07-16 21:00:00.111": not a valid representation (error: Failed to parse Date value '2022-07-16 21:00:00.111': Cannot parse date "2022-07-16 21:00:00.111": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSX', parsing fails (leniency? null)) at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 28] (through reference chain: apisample.app.sample.request.Json1Request["date"])
Json1Request.java
Java
1@Getter 2@Setter 3public class Json1Request implements Serializable { 4 5 private static final long serialVersionUID = -406584422054328917L; 6 7 @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss.SSS", iso=ISO.NONE) 8 private Date date; 9}
SampleController.java
Java
1@RestController 2public class SampleController { 3 4 @RequestMapping(value = "/json1", method = {RequestMethod.GET}) 5 public ResponseEntity<Json1Request> getJson1( 6 @RequestBody @Validated Json1Request request, BindingResult result) { 7 8 if (result.hasErrors()) { 9 result.getAllErrors().forEach(e -> { 10 System.out.println(e.toString()); 11 }); 12 return new ResponseEntity<>(HttpStatus.BAD_REQUEST); 13 } 14 return new ResponseEntity<>(request, HttpStatus.OK); 15 } 16}
実行コマンド
curl
1curl -i -d @json1.json -X GET -H "Content-Type: application/json" http://localhost:8081/apisample/json1
json1.json
JSON
1{ 2 "date": "2022-07-16 21:00:00.111" 3}
試したこと
メッセージで示唆されているように、パターンを"yyyy-MM-dd'T'HH:mm:ss.SSSX"変更したうえで、入力値を「2022-07-16T21:00:00.111」とすると、マッピングに成功します。
補足情報(FW/ツールのバージョンなど)
JDK: Oracle JDK 1.5
spring-webmvc version: 5.3.18
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/07/18 02:28 編集