How to prevent json output from relTargetType in spring -data-rest?

I create @RepositoryRestResource and export it as a recreation service as follows:

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

Problem: when I request content, I get the following excerpt:

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

Question: How can I prevent the publication of the relTargetType package and the "real" domain name?

+6
source share
2 answers

In your POJO:

If you don't want relTargetType in JSON at all:

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

If you just want to hide the package:

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

If you want to hide the package and return another domain name:

 public String getRelTargetType() { return "AlteredDomainName"; } 
+1
source

I am not familiar with Spring Rest Data, but as far as I can tell, it uses Jackson to handle JSON.

If this is true, I would suggest that your situation requires the use of mixing annotations , which are designed to control the serialization of classes that cannot be changed.

First create a simple blending class with a set of JsonIgnoreType annotations.

 @JsonIgnoreType public class OmitType {} 

Next, register the mix-in in your instance of ObjectMapper . As far as I can tell, you are accessing it in Spring Rest Data by following these instructions :

To add Jackson's own configuration to ObjectMapper used by Spring Data REST, override the configureJacksonObjectMapper method. This method will be passed to ObjectMapper [...]

In the configureJacksonObjectMapper method, register a mix with an unwanted type, like this:

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

Please note that RelTargetType.class is just a guess. Change the type that the field actually contains. This should force Jackson to ignore fields of this particular type whenever he encounters them.

Added:

In case the relTargetType field in MyContentEntity is actually just a string field, you can replace the mix with the following:

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

And register it should be changed to:

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

All Articles