简体   繁体   中英

Parse json contains array and object

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<>() {
            });

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
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM