Home > Back-end >  Parse json contains array and object
Parse json contains array and object

Time:12-21

I have JSON from payfort to read the transactions, tried to parse it to POJO but always gave to me the mismatch erorr

[
  [
    {
      "response_code": "04000",
      "card_holder_name": null,
      "acquirer_mid": "***",
      "payment_link_id": null,
      "order_description": "21882 - SAR"
    }
  ],
  {
    "data_count": 70
  }
]

This is my root pojo and I parse it using string

@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class DownloadReportResponse {

    private TransactionCount transactionCount;

    private List<TransactionsResponse> transactions;

}

Parsing :

   List<DownloadReportResponse> properties = new ObjectMapper().readValue(report, new TypeReference<>() {
            });

CodePudding user response:

Expanding on my comment, you could try something like this:

ObjectMapper om = new ObjectMapper();

//read the json into a generic structure    
JsonNode tree = om.readTree(json);
    
//check if the top level element is an array
if(tree.isArray()) {
  //iterate over the elements
  tree.forEach(element -> {
    //distinguish between nested list and object
    if(element.isArray()) {
      List<TransactionsResponse> responses = om.convertValue(element, new TypeReference<List<TransactionsResponse>>(){});
      //do whatever needed with the list
    } else if(element.isObject()) {
      TransactionCount txCount = om.convertValue(element, TransactionCount .class);  
      //use the count as needed
    }
  });
}

This depends on the knowledge that you get an array which contains an inner array of TransactionsResponse elements or objects of type TransactionCount but nothing else.

However, if you have a chance to modify the response I'd suggest you shoot for something like this which is way easier to parse and understand:

{
  "transactions":[ ... ],
  "transactionCount": {
    "data_count": 70
  }
}
  • Related