I have a question about consuming webservices with JSON/Gson because my new webservice delivers other strings than my old webservice. My new webservice is generated by Strapi 4 and I have no possibility to change it.
My Java application worked with JSON strings like this from my old webservice:
[
{
"nachname": "Studi1",
"contactWebServiceDTO": [
{
"emailAddress": "[email protected]",
"db_Id": 10,
"dateCreated": "May 10, 2022 10:33:14 AM",
"dateUpdated": "Feb 7, 2023 9:12:28 AM",
"dtype": "Contact"
}
],
"db_Id": 792,
"dateCreated": "Feb 26, 2021 2:11:19 PM",
"dateUpdated": "May 6, 2022 10:01:02 AM",
"dtype": "Person"
}
]
I converted it into Java objects with Gson like this:
JSONArray jsonArrayFromRest = new JSONArray(jsonString);
Gson gson = new Gson();
GsonBuilder builder = new GsonBuilder();
gson = builder.create();
if(identifiableWebServiceDTO instanceof PersonWebServiceDTO) {
PersonWebServiceDTO personWebServiceDTO = new PersonWebServiceDTO();
for (int i = 0; i < jsonArrayFromRest.length(); i++) {
String jsonObjectAsString = jsonArrayFromRest.getJSONObject(i).toString();
personWebServiceDTO = gson.fromJson(jsonObjectAsString, PersonWebServiceDTO.class);
dTOList.add(personWebServiceDTO);
}
}
Corresponding classes are:
public class IdentifiableWebServiceDTO {
protected long db_Id;
protected Date dateCreated, dateUpdated;
protected String dtype;
//Getter, Setter...
}
public class PersonWebServiceDTO extends IdentifiableWebServiceDTO {
private String nachname;
private List<ContactWebServiceDTO> contactWebServiceDTO;
// ...Setter/Getter
}
public class ContactWebServiceDTO extends IdentifiableWebServiceDTO {
private String emailAddress = null;
//Getter, Setter...
}
The new webservice delivers a string that nests every object in the string "data :[]" and the attributes in the string "attributes{}".
{
"data": [
{
"id": 1,
"attributes": {
"name": "Nicole",
"createdAt": "2024-03-27T06:55:54.668Z",
"updatedAt": "2024-03-27T06:56:18.843Z",
"publishedAt": "2024-03-27T06:56:18.841Z",
"mycontacts": {
"data": [
{
"id": 1,
"attributes": {
"address": "addressFromNicole",
"createdAt": "2024-03-27T06:56:09.438Z",
"updatedAt": "2024-03-27T06:56:11.625Z",
"publishedAt": "2024-03-27T06:56:11.619Z"
}
},
{
"id": 2,
"attributes": {
"address": "secondAddressFromNicole",
"createdAt": "2024-03-27T06:56:40.962Z",
"updatedAt": "2024-03-27T06:56:41.709Z",
"publishedAt": "2024-03-27T06:56:41.706Z"
}
}
]
}
}
}
],
"meta": {
"pagination": {
"page": 1,
"pageSize": 25,
"pageCount": 1,
"total": 1
}
}
}
Do you have an idea how I can convert this structure into my old Java objects in a simple way?