如何将字符串对象解析为json对象

时间:2015-01-28 18:41:44

标签: java arrays json jsp bufferedreader

我在JSP页面中接收缓冲区中的一些信息,我设法用它构建一个数组。我的问题是,如何将此字符串对象解析为json对象而不是获取值,以便每行在notepad.txt行上打印它。

获取缓冲数据的JSP页面

    <%@ page import="java.io.BufferedReader"%>
<%
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();

        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": []
    }
  ]
]

试图简化我的问题,我需要解析这个数组,以每行一行的notepad.txt打印。

1 个答案:

答案 0 :(得分:0)

您可以使用org.json库来解析JSON对象,它非常轻量级且非常易于使用。  org.json 你可以导入库并使用它在你的情况下创建一个JSON对象或JSON数组,就像这样。 :

body ; // Your JSON String 
JSONArray jArray = new JSONArray(body);
System.out.println(jArray.get(0).get("summary").toString());

希望这可以帮助你。