Yves Calaci
Yves Calaci

Reputation: 1129

Set @JsonProperty name using Spring's Expression Language (from application properties)

Suppose I have a Foo class like this:

public class Foo {

    @JsonProperty("${PROPERTY_NAME_FROM_APP_PROPERTIES}")
    private String foo;
    
}

How would we achieve dynamic JSON property name using SpEL?

Upvotes: 2

Views: 1366

Answers (2)

Yves Calaci
Yves Calaci

Reputation: 1129

You can create a custom JacksonAnnotationIntrospector and override Spring's default ObjectMapper:

@Configuration
public class JacksonConfig {

    @Bean
    @Primary
    public ObjectMapper objectMapper(Environment environment) {
        ObjectMapper mapper = new ObjectMapper();

        mapper.setAnnotationIntrospector(new ExpressionLanguageJacksonAnnotationIntrospector(environment));

        return mapper;
    }

    public static class ExpressionLanguageJacksonAnnotationIntrospector extends JacksonAnnotationIntrospector {

        private final Environment environment;
        
        public ExpressionLanguageJacksonAnnotationIntrospector(Environment environment) {
            this.environment = environment;
        }

        @Override
        public PropertyName findNameForSerialization(Annotated annotated) {
            PropertyName name = super.findNameForSerialization(annotated);

            if (name == null) {
                return null;
            }

            return PropertyName.construct(environment.resolvePlaceholders(name.getSimpleName()), name.getNamespace());
        }

    }

}

Upvotes: 2

Gary Russell
Gary Russell

Reputation: 174564

You cannot; the annotation is processed by Jackson, not Spring.

Upvotes: 0

Related Questions