简体   繁体   English

从配置动态读取@JsonProperty

[英]Read @JsonProperty dynamically from config

I am developing a Spring boot application which uses Jackson annotations. 我正在开发一个使用Jackson注释的Spring引导应用程序。

I want to read value of @JsonProperty from a config, instead of using constant string. 我想从配置中读取@JsonProperty值,而不是使用常量字符串。

Example JSON input JSON输入示例

{"s":12}

Code

I want to read property from my config: 我想从我的配置中读取属性:

@JsonProperty("${myconfig.fieldAlias.stream}")
private Integer stream;

instead of 代替

@JsonProperty("s")
private Integer stream;

Issue While executing the code above using config: 问题在使用config执行上述代码时:

variable "s" is not identified as stream 变量“ s”未标识为流

unless I use constant @JsonProperty("s") , which is not desired. 除非我使用常量@JsonProperty("s") ,否则这是不希望的。

Is it possible to use dynamic JsonProperty values? 是否可以使用动态JsonProperty值? If so, what is the proper way to do so? 如果是这样,这样做的正确方法是什么?

The name given to @JsonProperty must be statically given. @JsonProperty的名称必须是静态的。 What you can do is to overwrite the given name dynamically, by implementing a custom serializer for the propery: 您可以做的是通过实现自定义序列化程序来动态覆盖给定名称:

public static class StreamSerializer extends JsonSerializer<Integer> {
    @Override public void serialize(Integer value, JsonGenerator jsonGenerator, SerializerProvider provider)
        throws IOException {
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField("s", your_dynamic_name_here);// dynamic field name
        jsonGenerator.writeEndObject();
    }
}

and use it like this: 并像这样使用它:

@JsonProperty("s")
@JsonSerialize(using = StreamSerializer.class)
private Integer stream;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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