0

This is one of my json response.I need to get the value of href.I don't know the number of times the items array is repeating.Is there any way to parse these type of json arrays.

 {"batch_header":
    {"payout_batch_id":"123"},
    "items":[
    {"transaction_status":"PENDING",
    "payout_batch_id":"56",
    "links":[
    {"href":"link"}
    ]}
    ],
    "items":[
    {"transaction_status":"PENDING",
    "payout_batch_id":"78",
    "links":[
    {"href":"link"}
    ]
    }
    ]
    }

This is the code I tried.The code only work 1 for first loop and it break.

JSONObject obj = new JSONObject(response);
        JSONArray dataOuter = obj.getJSONArray("items");
        for (int i = 0; i < dataOuter.length() ; i++ ) {
            JSONObject jObject1 = dataOuter.getJSONObject(i);
            logger.info(" Items  "+jObject1);
            JSONArray dataInner = jObject1.getJSONArray("links");
            for (int j = 0; j < dataInner.length() ; j++ ) {
                JSONObject jItem = dataInner.getJSONObject(i);
                 responseURL = jItem.getString("href");
 }
}

1 Answers1

0

I would recommend the use of JsonPath library for yous use case. With that library you can use JsonPath expressions in Java to extract information.

The code will looks like:

import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;

import java.util.List;

public class JsonPathExample {
    public static void main(String[] args) {

        String myJson = "{\n" +
                "  \"batch_header\": {\n" +
                "    \"payout_batch_id\": \"123\"\n" +
                "  },\n" +
                "  \"items\": [\n" +
                "    {\n" +
                "      \"transaction_status\": \"PENDING\",\n" +
                "      \"payout_batch_id\": \"56\",\n" +
                "      \"links\": [\n" +
                "        {\n" +
                "          \"href\": \"link1\"\n" +
                "        }\n" +
                "      ]\n" +
                "    },\n" +
                "    {\n" +
                "      \"transaction_status\": \"PENDING\",\n" +
                "      \"payout_batch_id\": \"78\",\n" +
                "      \"links\": [\n" +
                "        {\n" +
                "          \"href\": \"link2\"\n" +
                "        }\n" +
                "      ]\n" +
                "    }\n" +
                "  ]\n" +
                "}";

        String myPath = "$['items'][*]['links'][*]['href']";

        DocumentContext jsonContext = JsonPath.parse(myJson);
        List<String> jsonPathResult = jsonContext.read(myPath);

        System.out.println(jsonPathResult);
    }
}

Output: ["link1","link2"]

P.D.: Your example json is invalid since it contains two items. I needed to modify it.

Ezequiel
  • 3,477
  • 1
  • 20
  • 28