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

解説

ObjectMapper を使って JSON 文字列を JsonNode に変換。
fields() メソッドでキーと値のペアを取得。
replaceAll("\.", "") を使ってキーの「.」を削除。
新しい ObjectNode に変更後のキーと値をセット。
writeValueAsString で JSON 文字列に変換。

ポイント

replaceAll("\.", "") で正規表現を使い、全ての「.」を削除。
ObjectNode を使い、新しい JSON を構築。

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

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 = entry.getKey().replaceAll("\\.", ""); // ドットを削除
    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,"addresscity":"Tokyo"}
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?