Java MappingJacksonJsonView:忽略字段而不使用@JsonIgnore

Java MappingJacksonJsonView:忽略字段而不使用@JsonIgnore,java,spring,jackson,Java,Spring,Jackson,我需要忽略POJO中的一些字段,因为它们被延迟加载和/或在某些情况下创建无限递归(父一对多子,子多对一父)。我的POJO位于另一个对Jackson、JSON等一无所知的罐子中 在不使用注释的情况下,如何有效地告诉Jackson忽略这些字段?通过配置将是最好的 谢谢您可以使用Java代码编写自定义序列化程序和反序列化程序,如下所示: class CustomSerializer extends JsonSerializer<ARow> { @Override public Class&

我需要忽略POJO中的一些字段,因为它们被延迟加载和/或在某些情况下创建无限递归(父一对多子,子多对一父)。我的POJO位于另一个对Jackson、JSON等一无所知的罐子中

在不使用注释的情况下,如何有效地告诉Jackson忽略这些字段?通过配置将是最好的


谢谢

您可以使用Java代码编写自定义序列化程序和反序列化程序,如下所示:

class CustomSerializer extends JsonSerializer<ARow> {
@Override
public Class<ARow> handledType() {
    return ARow.class;
}

public void serialize(ARow value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonProcessingException {
    jgen.writeStartObject();
    jgen.writeStringField("ounc", value.ounces.toLowerCase()); //Do this for all of your relevant properties..
    jgen.writeEndObject();
}
要使用Spring的
MappingJacksonJsonView设置此功能,您需要扩展自己的
ObjectMapper

public class MyCustomObjectMapper extends ObjectMapper {
    public MyCustomObjectMapper() {
        SimpleModule module = new SimpleModule("My Module", new Version(1, 0, 0, "SNAPSHOT"));
        module.addSerializer(new CustomSerializer());
        module.addSerializer(new CustomSerializer2());
        // etc
        this.registerModule(module);
    }
}
为它创建一个bean

<bean id="myCustomObjectMapper" class="com.foo.proj.objectmapper.MyCustomObjectMapper"/>

除了建议使用的自定义处理程序(以及可以使用的自定义处理程序),您还可以查看(或)。有了这些,您不仅可以使用@JsonIgnore,还可以使用@JsonManagedReference/@JsonBackReference,它们旨在保留一对一和一对多的关系(在序列化时被忽略,但在反序列化时重新连接!)

<bean id="myCustomObjectMapper" class="com.foo.proj.objectmapper.MyCustomObjectMapper"/>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
    <property name="objectMapper" ref="myCustomObjectMapper"/>
</bean>