1

我正在使用 Object Mapper,如果某些字段具有特定值,我想排除它们。

假设我有一个如下对象:

public static class Data 
{
    int id;
    int value;
}

假设该值很可能是 60。为了减少序列化数据长度,如果值等于 60,我希望它们仅使用 id 进行序列化。有没有办法实现这一点?

(顺便说一句。我试图通过为该确切值返回 null 来使用“忽略 null”功能,但不幸的是,这会破坏 bean 的可重用性)

4

1 回答 1

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
}

序列化器实现可能如下所示:

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]]
于 2013-10-01T13:17:42.247 回答