ジャクソンとヌルフィールドを無視する
1. 概要
このクイックチュートリアルでは、Jackson to ignore null fields when serializingをJavaクラスに設定する方法について説明します。
もっと深く掘り下げて、Jackson 2でできる他のクールなことを学びたい場合は、the main Jackson tutorialに進んでください。
参考文献:
2. クラスのNullフィールドを無視する
Jacksonでは、この動作をクラスレベルで制御できます。
@JsonInclude(Include.NON_NULL)
public class MyDto { ... }
または–より詳細に–フィールドレベルで:
public class MyDto {
@JsonInclude(Include.NON_NULL)
private String stringValue;
private int intValue;
// standard getters and setters
}
これで、nullの値が実際に最終的なJSON出力の一部ではないことをテストできるはずです。
@Test
public void givenNullsIgnoredOnClass_whenWritingObjectWithNullField_thenIgnored()
throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
MyDto dtoObject = new MyDto();
String dtoAsString = mapper.writeValueAsString(dtoObject);
assertThat(dtoAsString, containsString("intValue"));
assertThat(dtoAsString, not(containsString("stringValue")));
}
3. ヌルフィールドをグローバルに無視する
ジャクソンはconfiguring this behavior globally on the ObjectMapperも許可します:
mapper.setSerializationInclusion(Include.NON_NULL);
これで、このマッパーを介してシリアル化されたクラスのnullフィールドはすべて無視されます。
@Test
public void givenNullsIgnoredGlobally_whenWritingObjectWithNullField_thenIgnored()
throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
MyDto dtoObject = new MyDto();
String dtoAsString = mapper.writeValueAsString(dtoObject);
assertThat(dtoAsString, containsString("intValue"));
assertThat(dtoAsString, containsString("booleanValue"));
assertThat(dtoAsString, not(containsString("stringValue")));
}
4. 結論
nullフィールドを無視することは、JSON出力をより適切に制御する必要がある場合が多いため、このような一般的なJackson構成です。 この記事では、クラスに対してそれを行う方法を示します。 ただし、ignoring null values when serializing a Mapなどのより高度な使用例があります。
これらすべての例とコードスニペットの実装は、my Github projectにあります。