我有一个Class So,如下所示:
@Entity
@Table(name = "so", schema = "public")
public class So implements java.io.Serializable , IBusiness {
private int idSo;
private Set<PartOrder> partOrders = new HashSet<PartOrder>();
public So() {
}
@Id
@SequenceGenerator(name = "seqGenerator", sequenceName = "so_seq", allocationSize=1, initialValue=1)
@GeneratedValue(generator="seqGenerator", strategy=GenerationType.SEQUENCE)
@Column(name = "id_so", unique = true, nullable = false)
public int getIdSo() {
return this.idSo;
}
public void setIdSo(int idSo) {
this.idSo = idSo;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "so")
public Set<PartOrder> getPartOrders() {
return this.partOrders;
}
public void setPartOrders(Set<PartOrder> partOrders) {
this.partOrders = partOrders;
}
}
我有一个返回带有SO的Json的方法。但我不希望partOrders属性包含在响应json中。我在属性上使用@JsonIgnore但是现在,我有另一个接收SO对象的方法,我需要获取partOders。
问题是:有没有办法指定何时忽略属性(在特定方法中)?
先谢谢!
答案 0 :(得分:1)
您可以使用带有FilterProvider
@JsonFilter
注释为您的POJO指定过滤器名称。SimpleBeanPropertyFilter
的实例附加到过滤器名称。该类有两种基于属性名称的过滤器工厂方法。以下是注释声明的示例:
@JsonFilter("filter properties by name")
public class So {
public String alwaysWrite = "alwaysWriteValue";
public String somtimeIgnore = "somtimeIgnoreValue";
}
这是一个方法,它指定一个忽略somtimeIgnore
属性
public void dontWriteSomtimes(So so) {
ObjectMapper mapper = new ObjectMapper();
FilterProvider filters = new SimpleFilterProvider()
.addFilter("filter properties by name", SimpleBeanPropertyFilter.serializeAllExcept("somtimeIgnore"));
ObjectWriter writer = mapper.writer(filters);
try {
System.out.println(writer.writeValueAsString(so));
} catch (Exception e) {
e.printStackTrace();
}
}
输出:
{"alwaysWrite":"alwaysWriteValue"}
这是一个写一切的方法:只分配一个不存在的或空的属性:
public void writeEveryting(So so) {
ObjectMapper mapper = new ObjectMapper();
FilterProvider filters = new SimpleFilterProvider()
.addFilter("filter properties by name", SimpleBeanPropertyFilter.serializeAllExcept(""));
ObjectWriter writer = mapper.writer(filters);
try {
System.out.println(writer.writeValueAsString(so));
} catch (Exception e) {
e.printStackTrace();
}
}
输出:
{"alwaysWrite":"alwaysWriteValue","somtimeIgnore":"somtimeIgnoreValue"}
答案 1 :(得分:0)
你为你的班级添加了jSON ignore注释。我认为它会克服你的要求。你可以在这里留下不需要的财产。
@JsonIgnoreProperties(ignoreUnknown = true)
class ClassName{
}