Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to consume JSON Webservice from java client?

public void doView(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException {

    Map countryList = new HashMap();

    String str = "http://10.10.10.25/TEPortalIntegration/CustomerPortalAppIntegrationService.svc/PaymentSchedule/PEPL/Unit336";

    try {
        URL url = new URL(str);

        URLConnection urlc = url.openConnection();

        BufferedReader bfr = new BufferedReader(new InputStreamReader(urlc.getInputStream()));

        String line, title, des;

        while ((line = bfr.readLine()) != null) {

            JSONArray jsa = new JSONArray(line);

            for (int i = 0; i < jsa.length(); i++) {
                JSONObject jo = (JSONObject) jsa.get(i);

                title = jo.getString("Amount"); 

                countryList.put(i, title);
            }

            renderRequest.setAttribute("out-string", countryList);

            super.doView(renderRequest, renderResponse);
        }
    } catch (Exception e) {

    }
}

I am trying to access json object from liferay portlet class and I want to pass an array of values of any json field to the jsp page.

like image 966
Boat Avatar asked Jun 19 '26 10:06

Boat


1 Answers

You need to read the full response before converting it into a JSON array. This is because each individual line in the response is going to be an (invalid) JSON fragment, which cannot be parsed in isolation. With slight modifications your code should work, highlights below:

// fully read response
final String line;
final StringBuilder builder = new StringBuilder(2048);

while ((line = bfr.readLine()) != null) {
    builder.append(line);
}

// convert response to JSON array
final JSONArray jsa = new JSONArray(builder.toString());

// extract out data of interest
for (int i = 0; i < jsa.length(); i++) {
    final JSONObject jo = (JSONObject) jsa.get(i);
    final String title = jo.getString("Amount"); 

    countryList.put(i, title);
}
like image 86
Perception Avatar answered Jun 22 '26 04:06

Perception



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!