このクラスのカスタム シリアライザーを作成できます。たとえば、クラスは次のようになります。
@JsonSerialize(using = DataJsonSerializer.class)
class Data {
public static final int DEFAULT_VALUE = 60;
private int id;
private int value = DEFAULT_VALUE;
//getters, setters, toString, other
}
シリアライザーの実装は次のようになります。
class DataJsonSerializer extends JsonSerializer<Data> {
@Override
public void serialize(Data value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeStartObject();
jgen.writeFieldName("id");
jgen.writeNumber(value.getId());
if (value.getValue() != Data.DEFAULT_VALUE) {
jgen.writeFieldName("value");
jgen.writeNumber(value.getValue());
}
jgen.writeEndObject();
}
}
使用例:
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.type.CollectionType;
public class JacksonProgram {
public static void main(String[] args) throws IOException {
List<Data> datas = new ArrayList<Data>(10);
for (int index = 0; index < 10; index++) {
Data data = new Data();
data.setId(index);
data.setValue(index < 6 ? Data.DEFAULT_VALUE : index);
datas.add(data);
}
System.out.println(datas);
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(datas);
System.out.println(json);
CollectionType collectionType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, Data.class);
List<Data> deserializedArray = mapper.readValue(json, collectionType);
System.out.println(deserializedArray);
}
}
上記のプログラムは次のように出力します:
[Data [id=0, value=60], Data [id=1, value=60], Data [id=2, value=60], Data [id=3, value=60], Data [id=4, value=60], Data [id=5, value=60], Data [id=6, value=6], Data [id=7, value=7], Data [id=8, value=8], Data [id=9, value=9]]
[{"id":0},{"id":1},{"id":2},{"id":3},{"id":4},{"id":5},{"id":6,"value":6},{"id":7,"value":7},{"id":8,"value":8},{"id":9,"value":9}]
[Data [id=0, value=60], Data [id=1, value=60], Data [id=2, value=60], Data [id=3, value=60], Data [id=4, value=60], Data [id=5, value=60], Data [id=6, value=6], Data [id=7, value=7], Data [id=8, value=8], Data [id=9, value=9]]