Reputation: 62336
I'm trying to convert the following object to 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;
}
using this code:
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");
}
}
For some reason, the output of getProductEntity()
continues to show up in the JSON. Since I'm using a view and it's not annotated I would expect it not to appear here. Am I using the view incorrectly or is there some other configuration somewhere I'm missing?
Upvotes: 0
Views: 906
Reputation: 80593
This is well documented behavior. Specifically:
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);
where false means that such properties are NOT included when enabling with a view. Default for this property is 'true'.
If you are on versions of Jackson less than 1.8 you should be able to modify your object mapper as shown in the code above and the 'default' properties will no longer be included in the serialized data. If you are on versions 1.9 or higher, then use the following code as a guide:
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));
Output:
{"priority":{"code":"high"}}
Note that when you configure the DEFAULT_VIEW_INCLUSION to false, that you will need to specify the properties to be included for a view, at every level of your object hierarchy.
Upvotes: 1