Java · Jackson JSON naming
Jackson snake_case ↔ camelCase
Java property 維持 camelCase,只在 serialization 邊界轉換外部 snake_case JSON。
單一 model/DTO 使用 @JsonNaming
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
public class UserProfile {
private String firstName;
private String avatarUrl;
}SnakeCaseStrategy 可把 firstName 對應到 first_name,減少每個 property 都加 annotation。
全應用規則使用 ObjectMapper
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
UserProfile profile = mapper.readValue(json, UserProfile.class);
String output = mapper.writeValueAsString(profile);PropertyNamingStrategies.SNAKE_CASE 可同時套用 serialization 與 deserialization 的外部 property 名稱。
例外使用 @JsonProperty
public class UserProfile {
@JsonProperty("user_id")
private String userId;
@JsonProperty("display_name")
private String displayName;
}少數不符合全域規則的外部名稱可使用明確 property mapping。
正式環境注意事項
- 清楚決定命名規則由 class、ObjectMapper 或 field 哪一層負責。
- naming strategy 改的是 JSON property 名稱,不會修改 string value。
- 多個外部名稱正規化成同一 property 時應視為 API contract 問題。
- 範例使用 Jackson 2.x package,請確認所用 major version 的 migration 文件。
線上測試 JSON 邊界
在實作前測試巢狀物件、陣列、排除鍵、stop paths、語意前綴、衝突與 key-only diff。
拖放 .json 檔案,或從裝置選取
檔案只會在瀏覽器中讀取。最大檔案大小:5 MB。
轉換後 JSON
{
"user_profile": {
"first_name": "Ada",
"created_at": "2026-09-12"
}
}解析、檔案讀取、格式化與鍵名轉換都在瀏覽器本機執行。JSON 不會傳送到轉換伺服器。