0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

SpringBootのRestControllerでJSONパラメータのフィールド名にダブルクォートが付いてないとエラーになる

Posted at

概要

SpringBoot 2.5でRestControllerを用意し、JSONをRequestBodyとして受け取る簡単な実装をしようとしたところ、以下のエラーが発生しました。

org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unexpected character ('t' (code 116)): was expecting double-quote to start field name; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('t' (code 116)): was expecting double-quote to start field name

原因

JSONをパース(解析)する際のエラーのようです。

expecting double-quote to start field name

フィールド名はダブルクォートで開始しろと。
つまり、JSONのフィールド名はダブルクォートで囲っていないと、SpringBootがJSONを処理する際に利用しているJacksonがExceptionを発生させるような仕組みとなっているようです。

実際に使ったJSONは以下のようなものです。

{
  taskName : "test02",
  status: 0,
  priority: 0
}

解決策

JSONのフィールド名をダブルクォートで囲ってあげればもちろんExceptionは回避できますが、
そんなことをしないで、ダブルクォートで囲っていないフィールド名であっても、正常に処理が出来るようにしてあげたいと思います。

application.ymlに以下のような定義をすることで回避できます。

application.yml
spring:
  jackson:
    parser:
      allow-unquoted-field-names: true

ちなみに、Jacksonをそのまま利用する場合、ダブルクォートのExceptionを回避するための設定としてALLOW_UNQUOTED_FIELD_NAMESの値をtrueに設定する方法がありますが、application.ymlに

spring:
  jackson:
    parser:
      allow_unquoted_field_names: true

という設定をしてしまうと、以下のようなYAMLの定義エラーが発生するので注意が必要です。

説明	リソース	パス	ロケーション	タイプ
'allow_unquoted_field_names' is an unknown 'com.fasterxml.jackson.core.JsonParser$Feature[AUTO_CLOSE_SOURCE, ALLOW_COMMENTS, ALLOW_YAML_COMMENTS, ALLOW_UNQUOTED_FIELD_NAMES, ...]'. Valid values are: [ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, ALLOW_COMMENTS, ALLOW_LEADING_DECIMAL_POINT_FOR_NUMBERS, ALLOW_MISSING_VALUES, ALLOW_NON_NUMERIC_NUMBERS, ALLOW_NUMERIC_LEADING_ZEROS, ALLOW_SINGLE_QUOTES, ALLOW_TRAILING_COMMA, ALLOW_UNQUOTED_CONTROL_CHARS, ALLOW_UNQUOTED_FIELD_NAMES, ALLOW_YAML_COMMENTS, AUTO_CLOSE_SOURCE, IGNORE_UNDEFINED, INCLUDE_SOURCE_IN_LOCATION, STRICT_DUPLICATE_DETECTION, allow-backslash-escaping-any-character, allow-comments, allow-leading-decimal-point-for-numbers, allow-missing-values, allow-non-numeric-numbers, allow-numeric-leading-zeros, allow-single-quotes, allow-trailing-comma, allow-unquoted-control-chars, allow-unquoted-field-names, allow-yaml-comments, auto-close-source, ignore-undefined, include-source-in-location, strict-duplicate-detection]	application-local.yml	/restcontroller-sample/src/main/resources	行 39	言語サーバー
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?