yangs.dev

Jackson SnakeCase / CamelCase One-Click Conversion

Jackson SnakeCase / CamelCase One-Click Conversion
yangs.dev·

Introduction

Let's start today's discussion

Today, a situation arose where a specific gateway required responses in snake_case instead of camelCase.

Developers traditionally hate repetitive work, and adding @JsonProperty to every key to change the format... is unrealistic.

Let's conveniently make the change with just one annotation.

Stop Using @JsonProperty!

I asked someone else to handle this task, and they plastered the Response object's Data Class with @JsonProperty annotations.

Of course, there's no problem with development or functionality. But it reduces code readability, and honestly, it's tedious.

Stop it, @JsonProperty!!

Let's Use @JsonNaming

With just one annotation, you can easily switch between snake_case and camelCase.

Let's look at the example code below.

        @JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy::class)
        data class Me(
            val id: Long,
            val userId: Long,
            val issueDate: LocalDateTime,
        )

If you write your code like this, you'll see the JSON generated as follows.

{
  "id" : 1,
  "user_id": 2,
  "issue_date" : "2021-02-02"
}

Pretty easy, right?

Conclusion

In the past, I didn't know about the @JsonNaming annotation either, and since I was new to Jackson, I used @JsonProperty / Gson's @SerializedName a lot. But while 1-2 keys are fine, once you hit 20-30 keys, things go downhill and maintenance becomes increasingly difficult. So it's better to maintain things conveniently like this. (It does feel like annotation hell, but anyway...)