Reputation: 417
We are consuming a third party API on server side which returns response as below class.
public class SourceParent {
private String ultimateParentId;
private String name;
private List<SourceChildren> children;
}
public class SourceChildren {
private String ultimateParentId;
private String immediateParentId;
private String childName;
private String level;
private List<SourceChildren> children
}
Children nesting can be up to any level.
We have to map above object to similar type of target (class structure) class i.e.
public class TargetParent {
private String ultimateParentId;
private String name;
private List<TargeChildren> children;
}
public class TargeChildren {
private String ultimateParentId;
private String immediateParentId;
private String childName;
private String level;
private List<TargeChildren> children
}
Mapping has to be done field by field. We can not return source object from our API to our consumers because if any field name or field changes in source object we don't want our consumers to change their code instead we would just change in the mapper.
Somebody please suggest how to do this mapping efficiently from source to target object in java (preferred java 8 and above);
I am trying to map as below, however got stuck as children can be up to any level.
public TargetParent doMapping(SourceParent source) {
TargetParent target = new Targetparent();
target.setUltimateParentId(source.getUltimateParentId);
.......
target.setChildren() // Don't to how to approach here
}
Appreciate you help!
Upvotes: 0
Views: 299
Reputation: 242
In your doMapping do this
targetParent.setChildren(sourceParent.children.stream().map(sourceChild -> doMappingForChild(sourceChild)).collect(Collectors.toList()));
And add this function below doMapping, this is a recurcive approach
public TargetChild doMappingForChild(SourceChild source){
TargetChild target = new TargetChild();
...other fields
target .setChildren(sourceParent.children.stream().map(sourceChild -> doMappingForChild(sourceChild)).collect(Collectors.toList()));
}
Upvotes: 1