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?

JavaでCSV出力時に特定の項目をゼロ埋めする方法(カスタムSerializer使用)

Last updated at Posted at 2025-08-26

とある案件でCSV出力の実装をした際、特定の項目に対して加工をする必要がありました。
そのときの実装内容をメモとして残します。

背景

業務システムの開発でCSV出力機能を実装する中で、
ある項目だけ、出力時にゼロ埋めして5桁に整形するという要件がありました。

その際に、JacksonのカスタムSerializerを使って対応したので、
備忘録として残しておきます。

環境

  • Java:17
  • フレームワーク:Spring Boot
  • CSV出力ライブラリ:Jackson(jackson-databind

やりたいこと

「在庫数」などの数値項目をCSV出力する際に、
常に5桁のゼロパディングで出力したい。

例:"12" → "00012"

カスタムSerializerの作成

Jacksonの StdSerializer を継承して、独自の文字列整形を行うクラスを作成します。

public class ZeroPadded5DigitSerializer extends StdSerializer<String> {

    public ZeroPadded5DigitSerializer() {
        super(String.class);
    }

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        String trimmed = (value == null) ? "" : value.trim();
        String padded = String.format("%05d", Integer.parseInt(trimmed));
        gen.writeString(padded);
    }
}

処理の流れ
・入力された文字列(例:"12")をトリム(前後の空白除去)
・Integer.parseInt() で整数に変換
・String.format("%05d") で5桁のゼロパディング
・"00012" のように整形し、JSON文字列として出力

DTOでの使い方
Serializerを使いたいフィールド(今回は「在庫数」)に
アノテーションを付けるだけでOKです。

@JsonProperty("在庫数")
@JsonSerialize(using = PlusZeroPadded5DigitSerializer.class)
private String stockCount;

出力結果のイメージ
たとえば、以下のようなCSVを出力したいとします。

商品コード,在庫数,登録日,更新日
123456789012345,00005,20250701,20250701
このように、「在庫数」の項目のみゼロ埋めされた形式で出力されます。

まとめ

CSV出力時に特定の項目だけ整形したいとき、
JacksonのカスタムSerializerを使えば柔軟に対応できます。

特にフォーマットやゼロ埋めなどの要件は業務でよく出るので、
使い回せる形でクラスを作っておくと便利です。

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?