I am currently building a JSON in java that will be used as a requestbody when calling a POST-endpoint. The class I need to build into a JSON looks like this:
public class EmployeeImport {
@SerializedName("Header")
private final Header header;
@SerializedName("Employees")
private final List<Employee> employees;
public EmployeeImport(final Header header,
final List<Employee> employees) {
this.header = header;
this.employees = employees;
}
I use GSON to produce a JSON from this class:
private String generateJSONForImport(final Employee employee, final Header header) {
final EmployeeImport employeeImport = new EmployeeImport(header, Arrays.asList(employee));
final Gson gson = new Gson();
final String json = gson.toJson(employeeImport);
System.out.println(json);
}
When printing the JSON, it looks like this:
{
"Header": {
"Date": "2021-01-14"
},
"Employees": [
{
"ValueOne": "lala",
"ValueTwo": "lalala"
}
]
}
But I need the JSON to include the class "EmployeeImport" as a wrapping object, like this:
{
"EmployeeImport": {
"Header": {
"Date": "2021-01-13"
},
"Employees": [{
"ValueOne": "lala",
"ValueTwo": "lalala"
}]
}
}
I've searched for a good solution for this, and I have seen that the annotation "@JsonTypeInfo" seems to fix this, but this seems to only work for the jackson-library.
Does anyone know a good solution for how this could be done with the GSON-library?