0

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 :-(.

Alex
  • 624
  • 1
  • 9
  • 12
  • Maybe it could help https://devqa.io/how-to-convert-java-map-to-json/ – Juan Caicedo Jun 11 '20 at 15:22
  • Hi Juan, as mentioned in my question: The HashMap does the trick, but I'd rather see a custom Object/ class. The answer can be that its not possible how I want it. But maybe it can be done easily. – Alex Jun 12 '20 at 06:22

2 Answers2

1

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

  • As stated I've tried that. The CustomSerializer will allow you to add tags to the property dynamically but not the property it self. The link shows the name "p" of the property. it is that I want to change. – Alex Jun 12 '20 at 06:19
  • 1
    The serialization on class example does the trick! I like the solution, Thanks! – Alex Jun 12 '20 at 11:55
0

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);
Alex
  • 624
  • 1
  • 9
  • 12