2

I am developing a Spring boot application which uses Jackson annotations.

I want to read value of @JsonProperty from a config, instead of using constant string.

Example JSON input

{"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:

variable "s" is not identified as stream

unless I use constant @JsonProperty("s"), which is not desired.

Is it possible to use dynamic JsonProperty values? If so, what is the proper way to do so?

Idriss Neumann
  • 3,760
  • 2
  • 23
  • 32

1 Answers1

0

The name given to @JsonProperty must be statically given. 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;
NiVeR
  • 9,644
  • 4
  • 30
  • 35
  • Thanks for your reply! I want to do similar thing for 20 different properties, some of which are of int type, some are of list of int type, some of string type, etc. Hence, I want to write a generalized custom serializer which can be used by any class with any type of properties. Is that possible? – Nikita Jain Jun 21 '18 at 05:08
  • Not really, you must know the static name of each property in deserialization phase if you want to personalise it. Probably just save it as it comes, and when you use it put it in hash map. – NiVeR Jun 21 '18 at 06:05
  • Okay! Thanks NiVer! This has been very helpful. – Nikita Jain Jun 21 '18 at 06:12
  • @NikitaJain welcome. If this answered your question you can mark it as answer. – NiVeR Jun 21 '18 at 06:36