Issue
I have this response from some call:
{
"response": [
{
"id": "12345678",
"name": "Name lastName",
"someBoolean": true
},
{
"id": "987654321",
"name": "Name2 lastName2",
"someBoolean": false
}
]
}
That response is inserted in class InformationResponse
:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@EqualsAndHashCode
public class InformationResponse {
private List<Information> info = new ArrayList<>();
}
The class Information
has the fields:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@EqualsAndHashCode
public class Information {
private String id = null;
private String name = null;
private Boolean someBoolean = null;
}
And I have a context
that must contain this list of Information
class, but inserted in the correct object.
The id was previously filled out, so I must compare the Id's that came from the response and insert them in the right object in my context
.
My context class:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@EqualsAndHashCode
public class MyContext {
private Information clientOne; //id 12345678
private Information clienteTwo; //id 987654321
}
So, how can I insert the items from response inside the right object in my context ?
something like:
if(myContext.getClientOne().getId().equals(response.getId()) {
// set the fields here
}
Solution
A method to find an Information
instance by the id may be implemented and used to populate the context:
public static Optional<Information> findInfoById(List<Information> list, String infoId) {
return list.stream()
.filter(i -> infoId.equals(i.getId()))
.findFirst();
}
Assuming that MyContext
class has an all-args constructor, the fields may be populated as :
List<Information> infoList = informationResponse.getInfo();
MyContext context = new MyContext(
findInfoById(infoList, "12345678").orElse(null),
findInfoById(infoList, "987654321").orElse(null)
);
or using appropriate getters/setters:
MyContext context; // initialized with clientOne / clientTwo set
List<Information> infoList = informationResponse.getInfo();
findInfoById(infoList, context.getClientOne().getId()).ifPresent(context::setClientOne);
findInfoById(infoList, context.getClientTwo().getId()).ifPresent(context::setClientTwo);
Answered By - Nowhere Man
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)