我正在尝试将以下对象转换为 JSON:
public class Product {
private ProductEntity productEntity;
private Priority priority;
public Product() {
}
public Product(ProductEntity productEntity, Priority priority) {
this.productEntity = productEntity;
this.priority = priority;
}
public ProductEntity getProductEntity() {
return productEntity;
}
private void setProductEntity(ProductEntity productEntity) {
this.productEntity = productEntity;
}
@JsonView({Views.ShutdownView.class})
public Priority getPriority() {
return priority;
}
使用此代码:
logger.info("Booting up: "+this);
mapper.getSerializationConfig().withView(Views.ShutdownView.class);
//recover previously saved queue if needed
if (getEntity().getQueue() != null && getEntity().getQueue().length > 0) {
try {
queue = mapper.readValue(getEntity().getQueue(), new TypeReference<ArrayList<JobSet>>() {});
//now that it's read correctly, erase the saved data
getEntity().setQueue(null);
workflowProcessService.save(getEntity());
} catch (IOException e) {
e.printStackTrace();
logger.info("Unable to parse JSON");
}
}
由于某种原因,getProductEntity()
的输出继续显示在 JSON 中。由于我使用的是 View 并且它没有注释,所以我希望它不会出现在这里。我是否错误地使用了 View ,或者是否缺少其他配置?
最佳答案
这是well documented behavior 。具体来说:
Handling of "view-less" properties
By default all properties without explicit view definition are included in serialization. But starting with Jackson 1.5 you can change this default by:
objectMapper.configure(SerializationConfig.Feature.DEFAULT_VIEW_INCLUSION, false);
其中 false 表示在使用 View 启用时不包含此类属性。此属性的默认值为“true”。
block 引用>如果您使用的 Jackson 版本低于 1.8,您应该能够修改您的对象映射器,如上面的代码所示,并且“默认”属性将不再包含在序列化数据中。如果您使用的是 1.9 或更高版本,请使用以下代码作为指导:
final ObjectMapper mapper = new ObjectMapper(); mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false); final ObjectWriter writer = mapper .writerWithView(Views.ShutdownView.class); final Product product = new Product(new ProductEntity("Widget", BigDecimal.valueOf(10)), new Priority("high")); System.out.println(writer.writeValueAsString(product));
输出:
{"priority":{"code":"high"}}
请注意,当您将 DEFAULT_VIEW_INCLUSION 配置为 false 时,您将需要指定 View 要包含的属性,每个> 对象层次结构的级别。
关于java - jackson 不会忽略未注释的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16969607/