Shiju K Babu Shiju K Babu - 4 months ago 19
JSON Question

Printing JSON object in JSP

I have a servlet which creates a JsonObject.

JsonObject jsonObject=new JsonObject();
jsonObject.addProperty("name", "john");
jsonObject.addProperty("name", "Smith");
jsonObject.addProperty("name", "Ram");

HttpSession session=request.getSession(true);
session.setAttribute("jsonObject", jsonObject);
RequestDispatcher rd = request.getRequestDispatcher("viewpage.jsp");
rd.forward(request, response);


And this is my JSP page

<%@page import="com.google.gson.JsonObject"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>View Json</title>
<%
JsonObject jsonObject=(JsonObject)session.getAttribute("jsonObject");
%>

</head>
<body>
<h6>JSON View</h6>
<br>
<%=jsonObject%>
</body>
</html>


But when i run this, the JSP file printing only the last data. The following is the output

JSON View


{"name":"Ram"}


How can i print the whole? Thanks

PSR PSR
Answer
jsonObject.addProperty("name", "john");
jsonObject.addProperty("name", "Smith");
jsonObject.addProperty("name", "Ram");

Here you used same key as "name".So the values are overriding.Try to use different names like

jsonObject.addProperty("name1", "john");
jsonObject.addProperty("name2", "Smith");
jsonObject.addProperty("name3", "Ram");