繁体   English   中英

如何在spring-data-rest中防止relTargetType的json输出?

[英]How to prevent json output of relTargetType in spring-data-rest?

我正在创建一个@RepositoryRestResource并将其导出为rest服务,如下所示:

@RepositoryRestResource(collectionResourceRel = "myContent", path = "myContent")
public interface MyContentRepository extends PagingAndSortingRepository<MyContentEntity, Long> {

}

问题:当我请求内容时,我得到以下摘录:

  "content" : [ {
    "value" : [ ],
    "rel" : null,
    "collectionValue" : true,
    "relTargetType" : "com.domain.MyContentEntity"
  } ],

问题:如何防止暴露relTargetType包和“真实”域名?

在您的POJO中:

如果您根本不想在JSON中使用relTargetType:

@JsonIgnore
public String getRelTargetType() {
    return relTargetType;
}

如果您只想隐藏包裹:

public String getRelTargetType() {
    return relTargetType.split("\\.")[2];
}

如果要隐藏包并返回其他域名:

public String getRelTargetType() {
    return "AlteredDomainName";
}

我不熟悉Spring Rest Data,但据我所知,它使用Jackson进行JSON处理。

如果确实如此,我建议您的情况要求使用Mix-in注释 ,这些注释用于控制无法修改的类的序列化。

首先使用JsonIgnoreType注释集创建一个简单的混合类。

@JsonIgnoreType
public class OmitType {}

接下来,在使用的ObjectMapper实例中注册混合。 据我所知,您可以按照以下说明在Spring Rest Data中访问它:

要将自己的Jackson配置添加到Spring Data REST使用的ObjectMapper中,请覆盖configureJacksonObjectMapper方法。 该方法将传递给ObjectMapper [...]

configureJacksonObjectMapper方法中,使用不需要的类型注册混合,如下所示:

objectmapper.addMixIn(RelTargetType.class, OmitType.class);

请注意, RelTargetType.class只是猜测。 更改为字段实际包含的任何类型。 这应该使Jackson在遇到它时忽略该特定类型的字段。

添加:

万一relTargetType现场MyContentEntity实际上只是一个字符串字段,将混入可以改变,而不是以下内容:

public abstract class OmitType {
    @JsonIgnore
    public abstract String getRelTargetType();
}

注册它应该改为:

objectmapper.addMixIn(MyContentEntity.class, OmitType.class);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM