我有一个 3d 库,它包含在我使用的类中,我想用 jackson 序列化为 json。
我想 jackson 对象A,但忽略类C中的字段,而无法更改类B和C上的源代码,这可能吗?
class A {
B b;
}
class B {
C c;
}
class C {
int field;
}
最佳答案
我相信您可以通过使用自定义序列化器来实现解决方案。
您可以通过 ObjectMapper 添加自定义序列化程序。我在下面创建了一个小型单元测试,演示了如何实现它:
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.module.SimpleModule;
import org.junit.Test;
import java.io.IOException;
public class JacksonSerializerTest {
@Test
public void test() throws Exception {
C c = new C("initially lowercase string in c");
B b = new B(c);
A a = new A(b);
SimpleModule module = new SimpleModule("MyCustomModule", new Version(1, 0, 0, null));
module.addSerializer(new CustomSerializerForC());
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);
String pretty = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(a);
System.out.println(pretty);
}
public class A {
private B b;
public A(B b) {
this.b = b;
}
public B getB() {
return b;
}
public void setB(B b) {
this.b = b;
}
}
public class B {
private C c;
public B(C c) {
this.c = c;
}
public C getC() {
return c;
}
public void setC(C c) {
this.c = c;
}
}
public class C {
private String value;
public C(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
public class CustomSerializerForC extends JsonSerializer<C> {
@Override
public Class<C> handledType() {
return C.class;
}
@Override
public void serialize(C c, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
String upperCase = c.getValue().toUpperCase();
jsonGenerator.writeString(upperCase);
}
}
}
关于java - Jackson 忽略子类 3 的属性 :d party,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21672721/