Reputation: 51
i am working on a spring application and using Spring Webclient to make REST call to an external service. as a result, i have this object :
{
"error": 0,
"message": "",
"totalItems": 1,
"entities": [
[
{
"entityName": "Field 1",
"entityValue": "String value 1"
},
{
"entityName": "Field 2",
"entityValue": "Date Value 2 in dd-mm-yyyy format"
}
]
]
}
now i would like to create a DTO that contains two fields (String field1 and Date field2) and tell mapstruct to populate field1 with the entityValue corresponding to entityName Field 1 and same thing for field 2. how can i achieve that in a smart way ? ideally without looping on all entityName/entityValue pairs in each entity.
for now i have two DTOs representing my REST result :
public class Wrapper {
private int error;
private String message;
private int totalItems;
private List<PairEntity> entities;
}
and
public class PairEntity {
private String entityName;
private String entityValue;
}
Upvotes: 3
Views: 8834
Reputation: 2357
A little looping is included...
if entityName
is unique, change your dto to use a Map<String, String>
or Map<String, PairEntity>
(key = entityName) instead of List<PairEntity>
. You'll need a custom jackson mapper or gson, depending which lib is in use...
Or create an new dto and convert the list to a map manually.
Then create a custom mapping in mapstruct and get the values from the map.
https://www.baeldung.com/java-list-to-map
https://www.baeldung.com/jackson-deserialization
https://www.baeldung.com/mapstruct-custom-mapper
Upvotes: 2