如何在jsp中显示Json对象

时间:2013-12-24 07:48:00

标签: java json jsp gson

我是jsp的新手。我有一个JSON编码

{"eventDetails":[{"startDate":1387175589253,"eventJSON":"{\"userIp\":\"***.***.***.**\",\"organizationUid\":\"4261-5404a609bd14\",\"userAgent\":\"Restlet-Framework\/2.1m3\",\"currentSessionToken\":\"9f3ee5b076-27dbead458ca\",\"endTime\":1312,\"apiKey\":\"b6bd9-30849cf17727\",\"startTime\":13853,\"sessionToken\":null,\"eventId\":\"4731d1-adb6-10faaa3ee269\",\"userUid\":null,\"userId\":1,\"context\":\"\/v2\/account\/loginas\/anonymous\",\"eventName\":\"user-loginAs\""

我需要将eventJSON对象显示为原始数据:

{\"userIp\":\"204.236.177.80\",\"organizationUid\":\"4261739e-ccae-11e1-adfb-5404a609bd14\",\"userAgent\":\"Restlet-Framework\/2.1m3\",\"currentSessionToken\":\"9f3ee54a-4f5f-b076-27d8ca\",\"endTime\":1387175589312,\"apiKey\":\"b6b8-4ad5-96d9-3084927\",\"startTime\":1387175589253,\"sessionToken\":null,\"eventId\":\"478e8-4ed1-adb6-10faaa3ee269\",\"userUid\":null,\"userId\":11878,\"context\":\"\/v2\/act\/lonas\/anonymous\",\"eventName\":\"user-loginAs\"}

如何使用gson显示eventJSON并使用c:out进行打印。

JSP页面

<tr id="datalogList-${gC.index}">
<td id = "eventName-${gC.index}">
<c:out value="${datalog.eventName}" />
</td>   
<td id = "startTime-${gC.index}">
<c:out value="${datalog.startTime}" />
</td>  
<td id = "endTime-${gC.index}">
<c:out value="${datalog.endTime}" />
</td>
<td id = "apiKey-${gC.index}"></a>
<c:out value="${datalog.apiKey}" />
</td>
</tr> 

爪哇

  Datalogging[]  logevents = (Datalogging[]) gson.fromJson(eventValueList.toString(),Datalogging[].class);

感谢阅读。

1 个答案:

答案 0 :(得分:4)

  1. 您可以将其作为JavaScript变量:

    var persons = [ {“name”:“John Doe”,“address”:“Main Street 1”}, {“name”:“Jane Doe”,“地址”:“Baker Street 1”}, {“name”:“Jack Doe”,“address”:“Church Street 1”}  ];

  2. 我建议使用jQuery从中创建一个HTML表。

    <!DOCTYPE html>
        <html lang="en">
          <head>
            <title>Test</title>
            <script src="http://code.jquery.com/jquery-latest.min.js"></script>
            <script>
                var persons = [
                    { "name": "John Doe", "address": "Main Street 1" },
                    { "name": "Jane Doe", "address": "Baker Street 1" },
                    { "name": "Jack Doe", "address": "Church Street 1" }
                ];
                $(document).ready(function() {
                    var table = $('<table/>').appendTo($('#somediv'));
                    $(persons).each(function(i, person) {
                        $('<tr/>').appendTo(table)
                            .append($('<td/>').text(person.name))
                            .append($('<td/>').text(person.address));
                    });
                });
            </script>
          </head>
          <body>
            <div id="somediv"></div>
          </body>
        </html>
    

    2。你将它作为Java String变量,如下所示:

    String jsonPersons = "["
        + "{ \"name\": \"John Doe\", \"address\": \"Main Street 1\" },"
        + "{ \"name\": \"Jane Doe\", \"address\": \"Baker Street 1\" },"
        + "{ \"name\": \"Jack Doe\", \"address\": \"Church Street 1\" }"
    + "]";
    

    然后我建议使用JSON解析器从中获取List,例如Google Gson:

    List<Person> persons = new Gson().fromJson(jsonPersons, new TypeToken<List<Person>>()       {}.getType());
    

    Person类看起来像这样:

    public class Person {
       private String name;
       private String address;
       // Add or generate getters/setters.
    }
    

    让servlet将它放在请求范围内并转发到JSP进行显示,如下所示:

    request.setAttribute("persons", persons); 
    request.getRequestDispatcher("/WEB-INF/persons.jsp").forward(request, response);
    

    在JSP中,使用JSTL迭代它:

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    ...
    <table>
     <c:forEach items="${persons}" var="person">
        <tr>
            <td>${person.name}</td>
            <td>${person.address}</td>
        </tr>
     </c:forEach>
    </table>
    

    3与2相同,你将它作为Java变量,但是你想在JSP中通过Ajax获取它。然后创建一个Servlet类,它在doGet()方法中执行以下操作:

    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json");
    response.getWriter().write(jsonPersons);
    

    并通过jQuery Ajax调用它,回调与1)相同。

    $(document).ready(function() {
      var table = $('<table/>').appendTo($('#somediv'));
      $.getJSON('url/to/servlet', function(persons) {
        persons.each(function(i, person) {
            $('<tr/>').appendTo(table)
                .append($('<td/>').text(person.name))
                .append($('<td/>').text(person.address));
        });
      });
    });