LoginSignup
34
34

More than 5 years have passed since last update.

Jackson で気が向いた時だけ一部フィールドの出力をしない

Last updated at Posted at 2012-12-12

Jackson でオブジェクトを JSON にシリアライズするときに、一部フィールドはシリアライズしたくないときは、フィールドやメソッドに @JsonIgnore を使います。

普段はシリアライズするけど、場合によってはシリアライズしたくない、といったケースでは、無視したいところだけ @JsonIgnore したインターフェースを作って、それを mix-in するときれいにできます。

JUnit向け検証コード
static class Obento {
    private final String syusyoku;
    private final String syusai;
    private final String fukusai;
    private final int price;
    public Obento(String syusyoku, String syusai, String fukusai, int price) {
        this.syusyoku = syusyoku;
        this.syusai = syusai;
        this.fukusai = fukusai;
        this.price = price;
    }
    public String getSyusyoku() { return syusyoku; }
    public String getSyusai() { return syusai; }
    public String getFukusai() { return fukusai; }
    public int getPrice() { return price; }
}

static interface OgoriView {
    @JsonIgnore String getPrice();
}

@Test public void test() {
    Obento o = new Obento("しろめし", "カレー", "福神漬", 780);

    {
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.valueToTree(o).toString());
        // {"syusyoku":"しろめし","syusai":"カレー","fukusai":"福神漬","price":780}
    }
    {
        ObjectMapper mapper = new ObjectMapper();
        mapper.getSerializationConfig().addMixInAnnotations(Obento.class, OgoriView.class);
        System.out.println(mapper.valueToTree(o).toString());
        // {"syusyoku":"しろめし","syusai":"カレー","fukusai":"福神漬"}
    }
}

View なんてのもありますが、一部だけ出力しないというケースには向いてません。上の例では getPrice 以外の全てのフィールドにビューのアノテーションを書かないといけなくなります。

参考:

34
34
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
34
34