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?

JacksonでJSONのキー名をキー名の変換マップで変換

Last updated at Posted at 2025-03-18

Java 17

HashMap を作成し、キー名の変換ルールを定義。
ObjectMapper を使い JSON を JsonNode に変換。
fields() で JSON のキーと値を取得し、HashMap で対応するキー名に変換。
変換後のデータを ObjectNode に追加し、JSON 文字列に変換。

String jsonStr = "{\"user.name\": \"Alice\", \"user.age\": 25, \"address.city\": \"Tokyo\"}";

// キー名の変換マップ
Map<String, String> keyMap = new HashMap<>();
keyMap.put("user.name", "username");
keyMap.put("user.age", "userAge");
keyMap.put("address.city", "city");

ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = null;
try {
	rootNode = mapper.readTree(jsonStr);
} catch (JsonProcessingException e) {
    // 実際のコードでは、例外スローして上位のクラスでキャッチしてログ出力などをすること
	// TODO Auto-generated catch block
	e.printStackTrace();
}

// 新しいオブジェクトに変換後のキーを格納
ObjectNode newRoot = mapper.createObjectNode();

Iterator<Map.Entry<String, JsonNode>> fields = rootNode.fields();
while (fields.hasNext()) {
    Map.Entry<String, JsonNode> entry = fields.next();
    String newKey = keyMap.getOrDefault(entry.getKey(), entry.getKey()); // マップにある場合は変換
    newRoot.set(newKey, entry.getValue());
}

// 新しいJSON文字列に変換
String newJsonStr = null;
try {
	newJsonStr = mapper.writeValueAsString(newRoot);
} catch (JsonProcessingException e) {
    // 実際のコードでは、例外スローして上位のクラスでキャッチしてログ出力などをすること
    // TODO Auto-generated catch block
	e.printStackTrace();
}
System.out.println("newJsonStr:" + newJsonStr);
newJsonStr:{"username":"Alice","userAge":25,"city":"Tokyo"}

複雑なJSONに対応する場合は以下のページ方法で実装すること
JavaのJacksonライブラリを使い、再帰的にJSONのキーを変換

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?