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?

Springでバラバラな数値キーのリクエストをMapで受け取る

Last updated at Posted at 2025-05-09

はじめに

@JsonAnySetterをセッターメソッドとして設定することで、SpringBoot REST APIで[key: number]: string;のように、固定フィールド(例えば field1)に加えて、バラバラな数値キー(例- 123, 456)を Map < Integer, String > として受け取る方法を紹介します。

1.TypeScript 側のJSON例

Modeltype.ts

type Model = { 
field1: string;
[key: number]: string;
}

2.Spring側の受け取りエンティティの定義方法

Model.java

public class Model {

private String field1;

private Map<Integer, String> extraFields = new HashMap<>();

public String getField1() {

return field1;

}

public void setField1(String field1) {

this.field1 = field1;

}

@JsonAnySetter

public void setExtraField(String key, String value) {

try {

Integer intKey = Integer.parseInt(key);

extraFields.put(intKey, value);

} catch (NumberFormatException e) {

// 非整数キーは無視するか、別の処理を追加可能

}

}

public Map<Integer, String> getExtraFields() {

return extraFields;

}

}

3.ポイント

@JsonAnySetter を使うことで、field1 以外の任意のプロパティをすべて Map に格納できます。

数値キーはJSON上では文字列( "123")なので、Java側で Integer に変換する必要があります。

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?