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

前端 未结 1 493
长发绾君心
长发绾君心 2021-01-15 17:10

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

1条回答
  •  北恋
    北恋 (楼主)
    2021-01-15 17:34

    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 employees=new ArrayList(); 
     }
    

    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 parseJson(String json,Class 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

    
    <%@ 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);
    %>
     
    
    
     
    

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

    0 讨论(0)
提交回复
热议问题