Reputation: 427
So, at a point in my Java app, I make a call to an API and it returns data as a string in this format:
String1
=
{
"data":{
"metadata":{
// something
}
"node":{
"edges":[
{//edge 1},
{//edge 2},
...
]
}
}
}
Now due to paginated data, I have to make the API call multiple times. Therefore, I have String1
, String2
, ..., StringN
.
Now I want to generate a StringComposite
that should leave out the other fields and combine all the edges
json objects to a list, and look like this:
{
"edges":[
{//edge 1},
{//edge 2},
{//edge 3},
{//edge 4},
...
]
}
How can I achieve this?
Upvotes: 1
Views: 197
Reputation: 19565
One possible solution:
For example, using Lombok @Data
and Jackson @JsonIgnoreProperties
annotations
@Data
public class Root {
private Data data;
}
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class Data {
// metadata field is skipped
private List<Edge> edges;
}
StringComposite
may be defined like this:@Data
@AllArgsConstructor
public class StringComposite {
private List<Edges> edges;
}
Root
POJOs, which are merged then into a single StringComposite
using Stream::flatMap
:ObjectMapper om = new ObjectMapper();
List<String> apiResponses = ...; // build list of API responses
List<Edge> mergedEdges = apiResponses
.stream()
.map(str -> try {
return om.readValue(str, Root.class);
} catch (JsonParseException | JsonMappingException jex) {
throw new IllegalArgumentException(jex);
}) // Stream<Root>
.flatMap(root -> root.getEdges().stream()) // Stream<Edge>
.collect(Collectors.toList()); // List<Edge>
StringComposite result = new StringComposite(mergedEdges);
Upvotes: 2