Alex
Alex

Reputation: 654

Dynamic property name when serializing json

Developing a REST Api using spring boot web, I want to return a class to RepsonseEntity having a dynamic property using Jackson . When returning an Array list with Persons the result needs to look like

{
  "pages" : 1,
  "pageSize" : 20,
  "persons" : []
}

When returning a list with animals it needs to look like

{
  "pages" : 1,
  "pageSize" : 20,
  "animals" : []
}

I now have a class

public class APIResponse { 
  private int pages;
  private int pageSize;
  private List<T> list;
  ...
}

@JsonProperty does not cut as its not dynamic. A @JsonSerialize(using = CustomSerializer.class) also does not cut it as it only allows me to 'wrap' the value with other tags. Im running out of options here so looking for help. My last resort would be returning a HashMap which does the trick, but I simply do not like the looks of it. Does anyone know if this can be done using Jackson. Other frameworks are not an option :-(.

Upvotes: 0

Views: 1184

Answers (2)

Alex
Alex

Reputation: 654

After some digging I settled with the following solution

public class ApiResponse { 
  private int pages;
  private int pageSize;


  ...
}

...
ApiResponse response = new ApiResponse();
...
List<Person> persons = new ArrayList<>();
...
//convert object to json
ObjectMapper mapper = new ObjectMapper(); 
JsonNode jsonNode = mapper.valueToTree(response);
objectNode = jsonNode.deepCopy();
//add the dynamic property
objectNode.set(resourceName, mapper.valueToTree(persons));
String json = mapper.writeValueAsString(node);

Upvotes: 1

Rama Kant yadav
Rama Kant yadav

Reputation: 26

You'd have to write a custom serializer for the entire class, i.e., a JsonSerializer

For more info check this: jackson-custom-serialization-on-class

For more info check this: jackson-dynamic-property-names

Upvotes: 1

Related Questions