我需要忽略POJO中的某些字段,因爲它們正在被加載和/或在某些情況下創建無限遞歸(Parent一對多Childs,Child many-一對父母)。我的POJO駐留在另一個罐子裏,對傑克遜,JSON等一無所知。MappingJacksonJsonView:忽略沒有使用@JsonIgnore的字段
我該如何有效地告訴傑克遜忽略這些字段而不使用註釋?通過配置將是最好的。
感謝
我需要忽略POJO中的某些字段,因爲它們正在被加載和/或在某些情況下創建無限遞歸(Parent一對多Childs,Child many-一對父母)。我的POJO駐留在另一個罐子裏,對傑克遜,JSON等一無所知。MappingJacksonJsonView:忽略沒有使用@JsonIgnore的字段
我該如何有效地告訴傑克遜忽略這些字段而不使用註釋?通過配置將是最好的。
感謝
你可以寫一個自定義序列化和解串器,使用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();
}
}
併爲此自定義序列與傑克遜註冊:
ObjectMapper m = new ObjectMapper();
SimpleModule testModule = new SimpleModule("MyModule", new Version(1, 0, 0, null));
testModule.addSerializer(new CustomSerializer());
m.registerModule(testModule);
用Spring的來設置這個,你w生病需要擴展自己的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 id="myCustomObjectMapper" class="com.foo.proj.objectmapper.MyCustomObjectMapper"/>
創建一個bean並將它注入到你的
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
<property name="objectMapper" ref="myCustomObjectMapper"/>
</bean>
除了被認爲自定義處理程序(並會工作),你也可以看看mix-in annotations(或this wiki page)。有了這些,您不僅可以使用@JsonIgnore,而且還可以使用@ JsonManagedReference/@ JsonBackReference,它們被設計爲保留一對一和一對多的關係(在序列化時被忽略,但在反序列化時重新連接!)。