我正在使用Object Mapper,如果它们具有特定值,则想要删除某些字段。
假设我有一个像下面这样的对象:
public static class Data
{
int id;
int value;
}
并且假设该值最有可能是60.为了减少序列化数据长度,如果值等于60,我希望它们仅使用id进行序列化。有没有办法实现这一点?
(顺便说一句。我试图通过为该确切值返回null来使用'ignore null'功能,但不幸的是,这会导致bean重用性)
答案 0 :(得分:0)
您可以为此课程编写自定义序列化程序。例如,您的课程可能如下所示:
@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
}
Serializer实现可能如下所示:
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]]