javajsonjson-deserializationjava-annotationslocaldatetime

Custom annotation from others annotations in java


I have date in json like:

{
   "date": "04/22/2022 16:01:01" 
}

and the class:

public class Foo{
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy HH:mm:ss")
    private LocalDateTime date;
}

where everything work fine.

It is posible to have annotation with @JsonDeserialize and @JsonFormat in it?

I was trying something like this

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.TYPE, ElementType.PARAMETER})
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy HH:mm:ss")
public @interface MyLocalDateTimeAnnotation{
}

Where class coud look like this:

public class Foo{
    @MyLocalDateTimeAnnotation
    private LocalDateTime date;
}

But it doesnt work.


Solution

  • You need to use @JacksonAnnotationsInside

    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'.

    Example:

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.TYPE, ElementType.PARAMETER})
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy HH:mm:ss")
    @JacksonAnnotationsInside
    public @interface MyLocalDateTimeAnnotation {
    }
    
    public class Foo{
        @MyLocalDateTimeAnnotation
        private LocalDateTime date;
    }