java - jackson 不会忽略未注释的字段

标签 java json jackson

我正在尝试将以下对象转换为 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”。

如果您使用的 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/

相关文章:

serialization - 我可以在 RestEasy 中指定用于方法结果转换的 jackson @JsonView 吗?

java - 当 Java 代码中存在两个组时,使用 OR 验证正则表达式组

java - 绑定(bind)java库Xamarin.Android

java - 如何使用特定于域的对象填充 DeserializationContext 以便在反序列化期间使用它们?

mysql - 如何将 select 语句结果转换为 JSONARRAY 并更新另一个表

java - Jackson:枚举实例方法以字符串形式返回值

json - 带有 Jackson 2.2 的 Spring MVC : "HttpMediaTypeNotAcceptableException: Could not find acceptable representation"

java - 如何在 jBullet 中创建运动对象?

java - 无法从用户表中获取所有 userRole = "ManagerRole"的位置

java - 如何创建具有这种特定结构的 JSON 数组?