Java Jackson不忽略未注字段
我正在尝试将以下对象转换为JSON:Java Jackson不忽略未注字段,java,json,jackson,Java,Json,Jackson,我正在尝试将以下对象转换为JSON: public class Product { private ProductEntity productEntity; private Priority priority; public Product() { } public Product(ProductEntity productEntity, Priority priority) { this.productEntity = produc
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");
}
}
logger.info(“启动:+this”);
mapper.getSerializationConfig().withView(Views.ShutdownView.class);
//如果需要,恢复以前保存的队列
如果(getEntity().getQueue()!=null&&getEntity().getQueue().length>0){
试一试{
queue=mapper.readValue(getEntity().getQueue(),new TypeReference(){});
//现在已正确读取,请删除保存的数据
getEntity().setQueue(null);
workflowProcessService.save(getEntity());
}捕获(IOE异常){
e、 printStackTrace();
info(“无法解析JSON”);
}
}
出于某种原因,getProductEntity()
的输出继续显示在JSON中。因为我使用的是一个视图,它没有注释,所以我希望它不会出现在这里。我是否使用了不正确的视图,或者缺少了其他配置?这是一个问题。具体而言:
“无视图”属性的处理
默认情况下,没有显式视图定义的所有属性都包含在序列化中。但从Jackson 1.5开始,您可以通过以下方式更改此默认设置:
objectMapper.configure(SerializationConfig.Feature.DEFAULT\u VIEW\u INCLUSION,false)代码>
其中false表示在启用视图时不包括这些属性。此属性的默认值为“true”
如果您使用的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));
输出:
{“优先级”:{“代码”:“高”}
请注意,当您将默认的“视图”包含配置为false时,将需要在对象层次结构的每个级别指定视图要包含的属性。是否有方法在整个应用程序范围内配置此属性,或者必须在每个实例中配置此属性?您所说的“应用程序范围”是什么意思?您正在实现一个JAX-RS应用程序吗?或者以其他方式保留应用程序范围的ObjectMapper
?我的意思是,除非手动覆盖,否则配置将应用于所有ObjectMapper实例。默认情况下不是否,如果您将这些实例创建为new ObjectMapper()
,则每次都必须配置。例如,与之相反,如果您正在编写一个JAX-RS应用程序,您可以只实现一个ContextProvider
。但我不知道您正在创建什么样的应用程序。