0

I have a method named getPayDetails() which return type is a string

pay.getPaymentDetails() of which return type is a string and it returns the below string

[
   {
      "mcTtid":201657083281,
      "cardLast4Digits":"0887",
      "paymentType":"CREDIT CARD",
      "originalPaymentCategory":{
         "code":"Q",
         "name":"CREDIT CARD"
      }
   },
   {
      "veTtid":21656148003,
      "cardLast4Digits":"4777",
      "paymentType":"GIFT CARD",
      "originalPaymentCategory":{
         "code":"Q",
         "name":"GIFT CARD"
      }
   },
   {
      "mcTtid":201625819,
      "cardLast4Digits":"8388",
      "paymentType":"GIFT CARD",
      "originalPaymentCategory":{
         "code":"w",
         "name":"GIFT CARD"
      }
   }
]

I need to extract the value of the attribute paymentType from the above string so the value of attribute paymentType in the above string is CREDIT CARD in a separate string variable. how can I do this?

James Z
  • 12,209
  • 10
  • 24
  • 44
  • Note that although the return _type_ is `String` (as per your description) it actually represents JSON and thus you need to parse that JSON. I assume this method actually does a webservice call or something similar and thus returns a JSON - if it is creating the JSON internally and you have to parse that again when doing a local call I'd consider this bad design. – Thomas Jan 18 '22 at 08:04

1 Answers1

0

I would recommend to use org.json library that is very easy.

After that something like this

import org.json.*;

String jsonString = ... ; //assign your JSON String here
JSONArray arr = new JSONArray(jsonString);
for (int i = 0; i < arr.length(); i++)
{
    String paymentType = arr.getJSONObject(i).getString("paymentType");
}
Pavel_K
  • 10,748
  • 13
  • 73
  • 186