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?

More than 1 year has passed since last update.

jacksonを使ってjson生成時に先頭文字を大文字にしたい

Posted at

やりたいこと

以下のようなクラスがあった場合に、

@Getter
public class SampleClass{
    private String propertyA;
    private String propertyB;
}

オブジェクトを変換すると、
{"propertyA":"hoge","propertyB":"fuga"}
のようになると思うのですが、
諸事情あって、以下のように送信したかったことがありました。
{"PropertyA":"hoge","PropertyB":"fuga"}

いちいち@JsonProperty()を書くのは面倒・・・

解決法

ObjectMapperのオプションで解決できました。

    ObjectMapper mapper = new ObjectMapper();
    // 以下のオプションを有効化!!
    mapper.setPropertyNamingStrategy(PropertyNamingStrategies.UPPER_CAMEL_CASE);
    try {
      String jsonData = mapper.writeValueAsString(form);
      System.out.println(jsonData);
    } catch (JsonProcessingException e) {
      e.printStackTrace();
    }

他にもスネークケースなどなどの変換も用意されていたので、お困りの方は見てみると楽できるかもしれません!

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?