Question

Working with Play Framework 2.2, making a RESTfull API.

In a model I'm using, I wanted to output(Json with Jackson) only the Id of a related object, not the entire object. I found how to do that, as follows:

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonIdentityReference(alwaysAsId = true)
@JsonIgnore
public Object myObject;

The Json output will contain a JsonNode "myObjectId: 1". For instance.

The IdentityInfo and IdentityReference take care of this.

The problem is, wherever I want this, I have to paste down these 3 lines, along with any other annotations that need to be present for a certain field. This get grow too large and I'm trying to create just 1 custom annotation that does all these things together.

Is this possible, and how? A link where I can read about it or an example would be appreciated.

Était-ce utile?

La solution

To solve your problem you have to create an annotation annotated with JacksonAnnotationInside and annotations you want it to 'include'.

The Javadoc of that annotation says that it is:

Meta-annotation (annotations used on other annotations) used for indicating that instead of using target annotation (annotation annotated with this annotation), Jackson should use meta-annotations it has. This can be useful in creating "combo-annotations" by having a container annotation, which needs to be annotated with this annotation as well as all annotations it 'contains'.

For example for your case you'd have something like this:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@com.fasterxml.jackson.annotation.JacksonAnnotationsInside // this is important
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonIdentityReference(alwaysAsId = true)
public @interface MyCustomAnnotation {    
}

Then you can use it normally as you would Jackson annotations

@MyCustomAnnotation
public Object myObject;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top