Dave
Dave

Reputation: 19220

How do I use JSTL to output a value from a JSON string?

I’m using JBoss 7.1.3.As.Final and am building a Spring 3.2.11.RELEASE web application. On my JSP page I have this

${jsonString}

and what I would like to know is assuming this json string has an attribute “name”, how do I use JSTL (preferably no scriptlets) to print out the value associated with the “name” attribute to my page? Unsurprisingly, this doesn’t work

${jsonString[‘name’]}

Upvotes: 2

Views: 19633

Answers (1)

dsp_user
dsp_user

Reputation: 2121

If you can use third party libraries (e.g. Jackson), it should be fairly simple to accomplish this functionality. You will still have to create some java files to make this work though. First, create a POJO that matches your json data (in your case Employee could be something else but your POJO should match your fields).

public class Employee{
private String name;
private int age;
private String company;
public String getName(){
    return name;
}
public String getCompany(){
    return company;
}
public Integer getAge(){
    return age;
}
//implement setters
}

Next, create a list wrapper for Employee class like this

 public class EmployeeList {
 public List<Employee> employees=new ArrayList<Employee>(); 
 }

Now, create a JsonParser class (add Jackson library to the app classpath as well your app lib folder)

 import org.codehaus.jackson.map.ObjectMapper;

 public class JsonParser {  
 ObjectMapper objectMapper=new ObjectMapper();
 public <T> T parseJson(String json,Class<T> targetType)throws Exception{   
//uncomment this line if you want to ignore some fields, they dont have to   be in your POJO then    
 //objectMapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

 return objectMapper.readValue(json, targetType);
}
    }

Note that JsonParser can handle any type not just Employee. Now, in your jsp add the following import (add jstl-1.2.jar to your classpath as well as your app lib folder)

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

Add the following code to the body section

<body>
<%@ page import="java.util.List"%>
<%@ page import="apps.simpleweb.json.JsonParser"%>
<%@ page import="apps.simpleweb.data.Employee"%>
<%@ page import="apps.simpleweb.data.EmployeeList"%>
<%
//example json string ; note that employees matches the list name
String jsonString = "{  \"employees\":  [ {\"name\": \"Peter\", \"age\":  25, \"company\": \"XXXX\" },{ \"name\": \"Mark\", \"age\":45, \"company\": \"XXXX\"} ] }";

JsonParser parser = new JsonParser();
EmployeeList empList = parser.parseJson(jsonString, EmployeeList.class);
request.setAttribute("employeeList", empList.employees);
%>
 <c:forEach items="${employeeList}" var="employee" >
<c:out  value="Name : ${employee.name}" />
<c:out  value="Age : ${employee.age}"   />
 </c:forEach>

You should be able to avoid scriptlet code entirely if you move the parsing to the servlet.

Upvotes: 1

Related Questions