我正在尝试用Jackson序列化一个相当大的结构。
然而,它也试图导出很多我永远不需要的子结构(导致JsonMappingException: No serializer found for class)
那么,如何从序列化中排除类和命名空间呢?
或者,如何将类的属性标记为已排除/忽略?
发布于 2013-12-16 03:18:10
如果对要排除的子结构具有实际访问权限,请使用瞬态关键字。
Java瞬态是一个
关键字,当成员变量被持久化到字节流时,它会标记为不被序列化。当一个对象通过网络传输时,该对象需要被“序列化”。序列化将对象状态转换为串行字节。这些字节通过网络发送,并从这些字节重新创建对象。由java瞬态关键字标记的成员变量不会被传输,它们是故意丢失的。
http://en.wikibooks.org/wiki/Java_Programming/Keywords/transient
发布于 2013-12-16 03:24:20
请为排除类和命名空间提供一个示例,但对于您可能无法控制其源代码的属性,您可以在类型和字段上使用以下内容
@JsonIgnoreProperties(value = {"propertyName", "otherProperty"})Here's the javadoc.
下面是一个例子
@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。
https://stackoverflow.com/questions/20598607
复制相似问题