LoginSignup
24
13

More than 5 years have passed since last update.

Jackson が変換・出力対象とするもの

Posted at

Jackson の変換対象についてちょっと勘違いしていたことがあって、改めて調べ直したものをせっかくなので記事にしました。

Jackson が JSON に出力してくれるもの

以下が条件となります。(過不足があればご指摘ください)

  • public のフィールド
  • public のゲッター
    • 対応するフィールドがなくても、get で始まるメソッドがあれば出力対象となる
    • boolean の場合は、is で始まる名前も対象となる
      • can とか has などはならないっぽい
  • ここまでの条件に当てはまっていても、@JsonIgnore アノテーションをつけると対象外となる(つけるのはフィールドでもゲッターでもよい)

サンプル

百聞は一見に如かず、ということで実際にやってみましょう。

変換対象クラス

JacksonSampleObject.java
import com.fasterxml.jackson.annotation.JsonIgnore;

public class JacksonSampleObject {

    private Integer notOutputPrivate = 0;

    protected Integer notOutputProtected = 1;

    public Integer outputPublic = 2;

    private Integer outputPrivateWithPublicGetter = 3;

    public Integer getOutputPrivateWithPublicGetter() {
        return outputPrivateWithPublicGetter;
    }

    protected Integer outputProtectedWithGetter = 4;

    public Integer getOutputProtectedWithGetter() {
        return outputProtectedWithGetter;
    }

    private Integer getNotOutputPrivateGetter() {
        return 5;
    }

    protected Integer getNotOutputProtectedGetter() {
        return 6;
    }

    public Integer getOutputPublicGetter() {
        return 7;
    }

    @JsonIgnore
    public Integer notOutputPublicWithIgnoreAnnotation = 8;

    @JsonIgnore
    public Integer getNotOutputPublicGetterWithIgnoreAnnotation() {
        return 9;
    }

    private Boolean outputBoolean = true;

    public Boolean isOutputBoolean() {
        return outputBoolean;
    }

    public Integer isNotOutput() {
        return 10;
    }

    public Boolean getOutputBooleanGetter() {
        return true;
    }

    public Boolean canNotOutputBooleanMethod() {
        return false;
    }
}

実行クラス

JacksonSample.java
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JacksonSample {

    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        System.out.println(mapper.writeValueAsString(new JacksonSampleObject()));
    }
}

実行結果

{
  "outputPublic" : 2,
  "outputPrivateWithPublicGetter" : 3,
  "outputProtectedWithGetter" : 4,
  "outputBoolean" : true,
  "outputPublicGetter" : 7,
  "outputBooleanGetter" : true
}
24
13
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
24
13