我试图用Jackson序列化一个相当大的结构
但是,它也尝试导出我永远不需要的许多子结构(导致JsonMappingException: No serializer found for class
)
那么如何从序列化中排除类和命名空间呢?
或者,如何将我的类的属性标记为已排除/忽略?
答案 0 :(得分:1)
如果您实际访问了要排除的子结构,请使用 transient 关键字。
transient是一个Java关键字,它标记成员变量不是 在持久化为字节流时序列化。当一个物体是 通过网络传输,对象需要“序列化”。 序列化将对象状态转换为串行字节。那些字节 通过网络发送,并从那些重新创建对象 字节。由java transient关键字标记的成员变量不是 转移,他们故意丢失。
http://en.wikibooks.org/wiki/Java_Programming/Keywords/transient
答案 1 :(得分:0)
请举例说明排除类和命名空间但是对于您可能无法控制源代码的属性,您可以在类型和字段上使用以下内容
@JsonIgnoreProperties(value = {"propertyName", "otherProperty"})
这是一个例子
@JsonIgnoreProperties(value = { "name" })
public class Examples {
public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
Examples examples = new Examples();
examples.setName("sotirios");
Custom custom = new Custom();
custom.setValue("random");
custom.setNumber(42);
examples.setCustom(custom);
ObjectMapper mapper = new ObjectMapper();
StringWriter writer = new StringWriter();
mapper.writeValue(writer, examples);
System.out.println(writer.toString());
}
private String name;
@JsonIgnoreProperties(value = { "value" })
private Custom custom;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Custom getCustom() {
return custom;
}
public void setCustom(Custom custom) {
this.custom = custom;
}
static class Custom {
private String value;
private int number;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}
}
打印
{"custom":{"number":42}}
换句话说,它忽略了Examples#name
和Custom#value
。