您可以使用混入或
@JsonIgnoreProperties
对于这些示例,假定基本的ORM类和扩展名是:
public class DbItem { public String dbPropertyA; public String dbPropertyB;}
和
public class Person extends DbItem { public String index; public String firstName; public String lastName;}
分别。
使用混入混合是杰克逊从对象本身理解的反序列化指令的抽象。这是自定义第三方类的反序列化的一种方法。为了定义混入,必须创建一个抽象类并向中注册
ObjectMapper。混合定义示例
注册混音public abstract class PersonMixIn { @JsonIgnore public String dbPropertyA; @JsonIgnore public String dbPropertyB; @JsonIgnore public String index;}
@Testpublic void serializePersonWithMixIn() throws JsonProcessingException { // set up test data including parent properties Person person = makeFakePerson(); // register the mix in ObjectMapper om = new ObjectMapper() .addMixIn(Person.class, PersonMixIn.class); // translate object to JSON string using Jackson String json = om.writevalueAsString(person); assertFalse(json.contains("dbPropertyA")); assertFalse(json.contains("dbPropertyB")); assertFalse(json.contains("index")); System.out.println(json);}
@JsonIgnoreProperties
如果要避免创建类并配置
ObjectMapper,
@JsonIgnoreProperties可以使用注释。只需注释要序列化的类并列出要排除的属性。示例可序列化对象
实际观看@JsonIgnoreProperties({"index", "dbPropertyA", "dbPropertyB"})public class Person extends DbItem { public String index; public String firstName; public String lastName;}
@Testpublic void serializePersonWithIgnorePropertiesAnnotation() throws JsonProcessingException { // set up test data including parent properties Person person = makeFakePerson(); ObjectMapper om = new ObjectMapper(); // translate object to JSON string using Jackson String json = om.writevalueAsString(person); assertFalse(json.contains("dbPropertyA")); assertFalse(json.contains("dbPropertyB")); assertFalse(json.contains("index")); System.out.println(json);}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)