如何从Java客户端使用JSON Web服务?

问题描述:

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) {

    }
}

我正在尝试从liferay Portlet类访问json对象,并且希望将任何json字段的值数组传递给jsp页面.

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.

您需要先读取完整的响应,然后才能将其转换为JSON数组.这是因为响应中的每一行将是一个(无效的)JSON片段,无法单独对其进行解析.稍作修改,您的代码就可以正常工作,突出显示如下:

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);
}