简体   繁体   中英

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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