0

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<>() {
            });
1
  • That json is hard to parse automatically since in Java that outer array would have to be Object[] and thus there's no easy way for Jackson to know what to expect here. You might need to either provide a custom deserializer (which could delegate to the standard ones) or try to first parse the json into a generic structure and then deserialize the individual elements based on whether it is another array or an object - assuming you know what the types of those would be. Commented Dec 21, 2022 at 13:37

1 Answer 1

2

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
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.