3

Is it possible to rename JSON output fields in an object an arbitrary number of times when outputting with Jackson?

I can use a one-time JsonProperty as shown here,

How to map JSON field names to different object field names?

But suppose I have a single class which is used in multiple outputs. In each output, I want to have the flexibility of defining which name(s) to change.

public class Study implements Serializable {

   // Can vary as "id" / "studyId" depending on call
   private int id;

   // Can vary as "description" / "studyDescription" / "studyDesc" depending on call
   private String description;
}

Or do I need to create new objects for each case?

gene b.
  • 10,512
  • 21
  • 115
  • 227
  • 1
    Have you looked at Custom Deserializer? https://www.baeldung.com/jackson-deserialization. You could make the property name dynamic in a constructor of your Custom Deserializer. – Xavier Bouclet Jun 03 '19 at 16:01
  • Try to use `JsonAnyGetter` annotation. See: [How to use dynamic property names for a Json object](https://stackoverflow.com/questions/55684724/how-to-use-dynamic-property-names-for-a-json-object), [Adding a dynamic json property as java pojo for jackson](https://stackoverflow.com/questions/56245719/adding-a-dynamic-json-property-as-java-pojo-for-jackson), [Dynamic change of JsonProperty name using Jackson java library](https://stackoverflow.com/questions/55845478/dynamic-change-of-jsonproperty-name-using-jackson-java-library) – Michał Ziober Jun 04 '19 at 18:52

1 Answers1

0

Do refer: https://www.baeldung.com/json-multiple-fields-single-java-field

It's as simple as using @JsonAlias in combination with @JsonProperty annotation as below:

public class Study implements Serializable {

   // Can vary as "id" / "studyId" depending on call
   @JsonProperty("id")
   @JsonAlias("studyId")
   private int id;

   // Can vary as "description" / "studyDescription" / "studyDesc" depending on call
   private String description;
}

PS: Using @JsonProperty twice didn't work :D

tgallei
  • 827
  • 3
  • 13
  • 22