Jackson-Serialiser:序列化时忽略字段

时间:2019-07-24 13:42:13

标签: serialization jackson

我的情况要求更复杂的序列化。我有一个Available类(这是一个非常简化的片段):

public class Available<T> {
  private T value;
  private boolean available;
  ...
}

所以是POJO

class Tmp {
  private Available<Integer> myInt = Available.of(123);
  private Available<Integer> otherInt = Available.clean();
  ...
}

通常会导致

{"myInt":{available:true,value:123},"otherInt":{available:false,value:null}}

但是,我希望序列化器像这样渲染相同的POJO:

{"myInt":123}

我现在所拥有的:

public class AvailableSerializer extends JsonSerializer<Available<?>> {

  @Override
  public void serialize(Available<?> available, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException, JsonProcessingException {
    if (available != null && available.isAvailable()) {
      jsonGenerator.writeObject(available.getValue());
    }

    // MISSING: nothing at all should be rendered here for the field
  }

  @Override
  public Class<Available<?>> handledType() {
    @SuppressWarnings({ "unchecked", "rawtypes" })
    Class<Available<?>> clazz = (Class) Available.class;
    return clazz;
  }

}

测试

  @Test
  public void testSerialize() throws Exception {
    SimpleModule module = new SimpleModule().addSerializer(new AvailableSerializer());
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(module);

    System.out.println(objectMapper.writeValueAsString(new Tmp()));
  }

输出

{"myInt":123,"otherInt"}

谁能告诉我如何进行“ MISSING”操作?或者,如果我做错了一切,那该怎么办?

我的限制是我不希望开发人员一直向@Json...类型的字段添加Available注释。因此,上面的Tmp类是一个典型的使用类的外观示例。 如果可能的话...

2 个答案:

答案 0 :(得分:1)

Include.NON_DEFAULT

如果我们假设您的clean方法是通过以下方式实现的:

class Available<T> {

    public static final Available<Object> EMPTY = clean();

    //....

    @SuppressWarnings("unchecked")
    static <T> Available<T> clean() {
        return (Available<T>) EMPTY;
    }
}

您可以将序列化包含设置为JsonInclude.Include.NON_DEFAULT值,并且应跳过设置为EMPTY(默认)值的值。参见以下示例:

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;

import java.io.IOException;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        SimpleModule module = new SimpleModule();
        module.addSerializer(new AvailableSerializer());

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(module);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);

        System.out.println(objectMapper.writeValueAsString(new Tmp()));
    }
}

class AvailableSerializer extends JsonSerializer<Available<?>> {

    @Override
    public void serialize(Available<?> value, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException {
        jsonGenerator.writeObject(value.getValue());
    }

    @Override
    @SuppressWarnings({"unchecked", "rawtypes"})
    public Class<Available<?>> handledType() {
        return (Class) Available.class;
    }
}

上面的代码显示:

{"myInt":123}

自定义BeanPropertyWriter

如果您不想使用Include.NON_DEFAULT,则可以编写自定义BeanPropertyWriter并跳过所有需要的值。参见以下示例:

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        SimpleModule module = new SimpleModule();
        module.addSerializer(new AvailableSerializer());
        module.setSerializerModifier(new BeanSerializerModifier() {
            @Override
            public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
                List<BeanPropertyWriter> writers = new ArrayList<>(beanProperties.size());

                for (BeanPropertyWriter writer : beanProperties) {
                    if (writer.getType().getRawClass() == Available.class) {
                        writer = new SkipNotAvailableBeanPropertyWriter(writer);
                    }
                    writers.add(writer);
                }

                return writers;
            }
        });

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(module);

        System.out.println(objectMapper.writeValueAsString(new Tmp()));
    }
}

class AvailableSerializer extends JsonSerializer<Available<?>> {

    @Override
    public void serialize(Available<?> value, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException {
        jsonGenerator.writeObject(value.getValue());
    }

    @Override
    @SuppressWarnings({"unchecked", "rawtypes"})
    public Class<Available<?>> handledType() {
        return (Class) Available.class;
    }
}

class SkipNotAvailableBeanPropertyWriter extends BeanPropertyWriter {

    SkipNotAvailableBeanPropertyWriter(BeanPropertyWriter base) {
        super(base);
    }

    @Override
    public void serializeAsField(Object bean, JsonGenerator gen, SerializerProvider prov) throws Exception {
        // copier from super.serializeAsField(bean, gen, prov);
        final Object value = (_accessorMethod == null) ? _field.get(bean) : _accessorMethod.invoke(bean, (Object[]) null);
        if (value == null || value instanceof Available && !((Available) value).isAvailable()) {
            return;
        }

        super.serializeAsField(bean, gen, prov);
    }
}

上面的代码显示:

{"myInt":123}

答案 1 :(得分:0)

Michał Ziober回答之后,我不得不寻找与Include.NON_DEFAULT和默认对象有关的内容,并遇到this answer并解释Include.NON_EMPTY Google并未返回我首次研究(感谢Google)。

现在事情变得容易了,现在:

public class AvailableSerializer extends JsonSerializer<Available<?>> {

  @Override
  public void serialize(Available<?> available, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException, JsonProcessingException {
    if (available != null && available.isAvailable()) {
      jsonGenerator.writeObject(available.getValue());
    }
  }

  @Override
  public Class<Available<?>> handledType() {
    @SuppressWarnings({ "unchecked", "rawtypes" })
    Class<Available<?>> clazz = (Class) Available.class;
    return clazz;
  }

  @Override
  public boolean isEmpty(SerializerProvider provider, Available<?> value) {
    return value == null || !value.isAvailable();
  }

}

通过测试

  @Test
  public void testSerialize() throws Exception {
    SimpleModule module = new SimpleModule().addSerializer(availableSerializer);
    objectMapper.registerModule(module);
    objectMapper.configOverride(Available.class).setInclude(
        // the call comes from JavaDoc of objectMapper.setSerializationInclusion(...)
        JsonInclude.Value.construct(JsonInclude.Include.NON_EMPTY, JsonInclude.Include.ALWAYS));

    Tmp tmp = new Tmp();
    System.out.println(objectMapper.writeValueAsString(tmp));
    tmp.otherInt.setValue(123);
    System.out.println(objectMapper.writeValueAsString(tmp));
  }

和输出

{"myInt":123}
{"myInt":123,"otherInt":123}

因此,如果您赞成我的回答,请也赞成MichałZiober's,因为这也可以采用一种稍微不同的方法。