1

根据我尝试使用的视图,我的 JSON 中显示了不应显示的字段。我相信我正在正确编码使用 hte 视图...

ObjectMapperProvider

@Component
@Provider
public class ObjectMapperProvider implements ContextResolver<ObjectMapper> {

    @Override
    public ObjectMapper getContext(Class<?> aClass) {
        ObjectMapper objectMapper = new ObjectMapper();

        // http://wiki.fasterxml.com/JacksonJsonViews#Handling_of_.22view-less.22_properties
        objectMapper.configure(SerializationConfig.Feature.DEFAULT_VIEW_INCLUSION, Boolean.FALSE);

        return objectMapper;
    }
}

生成 JSON 的代码:

ObjectMapper mapper = new ObjectMapper();
mapper.getSerializationConfig().withView(Views.ShutdownView.class);

//persist the queue to the database
if (getQueue().size() > 0) {
    try {
        getEntity().setQueue(mapper.writeValueAsBytes(getQueue()));
    } catch(IOException e) {
        logger.severe("Unable to JSONify: "+getEntity());
        e.printStackTrace();
    }
}

我看到的部分 JSON 包括:

                 "uuid":"c0fbb88f-893e-4375-91a0-1ebb315e7ad7",
                 "inProduction":false,
                 "updated":null,
                 "created":1372346197000,

当唯一应该显示的字段是uuid

@javax.persistence.Column(name = "uuid", nullable = false, insertable = true, updatable = true, length = 128, precision = 0)
@Basic
@JsonView({Views.ShutdownView.class})
public String getUuid() {
    return uuid;
}

public void setUuid(String uuid) {
    this.uuid = uuid;
}

private Boolean inProduction;

@javax.persistence.Column(name = "in_production", nullable = false, insertable = true, updatable = true, length = 0, precision = 0)
@Basic
public Boolean getInProduction() {
    return inProduction;
}

public void setInProduction(Boolean inProduction) {
    this.inProduction = inProduction;
}

private Timestamp updated;

@javax.persistence.Column(name = "updated", nullable = true, insertable = true, updatable = true, length = 19, precision = 0)
@Basic
public Timestamp getUpdated() {
    return updated;
}

public void setUpdated(Timestamp updated) {
    this.updated = updated;
}

private Timestamp created;

@javax.persistence.Column(name = "created", nullable = false, insertable = true, updatable = true, length = 19, precision = 0)
@Basic
public Timestamp getCreated() {
    return created;
}

public void setCreated(Timestamp created) {
    this.created = created;
}
4

2 回答 2

1

有一些问题需要解决,然后才能正常工作

  • 您发布了您的代码,ObjectMapperProvider但在代码示例中您这样做new ObjectMapper()了,它不会有您的DEFAULT_VIEW_INCLUSION设置

  • withView方法返回一个新实例,它们不会修改调用它们的实例。此外,在这种情况下,您可能不想修改序列化配置。正确的代码是:mapper.writerWithView(Views.ShutdownView.class).writeValueAsBytes(getQueue())

于 2013-07-06T14:29:57.990 回答
0

您需要ObjectMapper像这样设置字段可见性:

mapper.setVisibility(PropertyAccessor.FIELD, Visibility.None)
于 2013-07-02T20:26:48.133 回答