How to consume JSON Webservice from java client?

2019-05-13 03:09发布

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.

1条回答
Summer. ? 凉城
2楼-- · 2019-05-13 03:38

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);
}
查看更多
登录 后发表回答