Debapratim Chakraborty
Debapratim Chakraborty

Reputation: 427

Parse Java String of JSON to keep only relevant fields

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

Answers (1)

Nowhere Man
Nowhere Man

Reputation: 19565

One possible solution:

  • Create a POJO to parse a single response from API like this, ignoring unneeded properties:

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;
}
  • The resulting StringComposite may be defined like this:
@Data
@AllArgsConstructor
public class StringComposite {
    private List<Edges> edges;
}
  • So, the input strings are parsed into a list/stream 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

Related Questions