无法将字符串转换为JSONArray JSP页面

时间:2015-01-28 20:41:30

标签: json string jsp

我正在尝试将字符串转换为JSP页面中的json数组,但它一直给我以下错误:

-The constructor JSONArray(String) is undefined

- The method get(String) is undefined for the type Object

我试图在JSON数组中获取正文内容来操纵它的结果。

这是我的JSP页面:

    <%@ page import="java.io.BufferedReader"%>
<%@ page import="org.json.simple.*"%>
<%@ page import="com.google.gson.*"%>
<%
try {

        String body = null;
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;

        try {

            // aqui está o ponto: tem que abrir uma stream e ler os bytes, não vem pronto.
            bufferedReader = request.getReader();



            char[] charBuffer = new char[128];
            int bytesRead = -1;

            // precisa ler todos os caracters do buffer de entrada do request.

            while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                stringBuilder.append(charBuffer, 0, bytesRead);
            }

        } catch (Exception ex) {
            throw ex;
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (Exception ex) {
                    throw ex;
                }
            }
        }


        // pronto aqui está o conteúdo da chamada
        body = stringBuilder.toString();

        JSONArray jArray = new JSONArray(body);

        System.out.println(jArray.get(0).get("summary").toString());

        System.out.println("Body:["+body+"]");


} catch (Exception e) {
    e.printStackTrace();
} finally {

}

%>

身体的结果 -

[
  [
    {
      "summary": {
        "externalInputs": [],
        "accessPointId": 2,
        "authorizedCount": 0,
        "closedTime": null,
        "detectedCount": 0,
        "endTime": 1422493644041,
        "enteredCount": 0,
        "eventId": 12760,
        "identifiedCount": 0,
        "openedTime": null,
        "siteId": 1,
        "startTime": 1422493583912,
        "systemFailure": null,
        "unlockedTime": null,
        "assistanceRequested": false,
        "blacklistedPersonDetected": false,
        "doorOpenedManually": false,
        "doorRemainedOpen": false,
        "hasEnded": true,
        "tailgatingDetected": false,
        "wasDoorOpened": false
      },
      "entityDetailList": []
    }
  ]
]

1 个答案:

答案 0 :(得分:0)

如果你想使用JSON,你必须定义页面的开头

<%@page import="org.json.JSONArray"%>
<%@page import="org.json.JSONObject"%>

或者如果你想使用Gson

你必须设置你的gson:

String json = "yourjson";
Gson gson = new Gson();
gson.toJson(json);
gson.get...