Sunday 7 September 2014

Converting Java object into JavaScript object

Recently I had a requirement to change a java object into JavaScript object when the request is submitted and response is received. I dint want to make a ajax call because the data was available when I received the response but i was not able to get that in JavaScript object from the request. I did Google and found some of the possible solution as per the link. The below code from the site was workable but I had a complex object


<script>  
    var myMap = {  
      <c:forEach items="${theMap}" var="item" varStatus="loop">  
        ${item.key}: '${item.value}' ${not loop.last ? ',' : ''}  
      </c:forEach>  
    };  
</script>  
and it require many levels of iteration and the creation of the same object with the above logic was difficult and thus it was better to go for ajax than creating the JavaScript object from the request.

Then i realized the object we are trying to create using the above logic is exactly same as the json object then perhaps sending json string and trying to convert that will be much more easier than doing the above logic. It was much more easier than the above logic so am pasting my test project for any one who require such requirements in future.

Simple pojo trying to convert.
Employee.java


package springapp.domain;

public class Employee {

    private String name;
    private String age;
    private Address address;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
    @Override
    public String toString() {
        return "Employee [name=" + name + ", age=" + age + ", address="
                + address + "]";
    }
    
} 

Address.java


package springapp.domain;

public class Address {

    private String street;
    private String city;
    public String getStreet() {
        return street;
    }
    public void setStreet(String street) {
        this.street = street;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    @Override
    public String toString() {
        return "Address [street=" + street + ", city=" + city + "]";
    }
    
}
 



class converting List of employee to json object and setting into request scope

JspVariableTest.java


package springapp.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import junit.framework.Test;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import springapp.domain.Address;
import springapp.domain.Employee;


public class JspVariableTest implements Controller{

    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        ModelAndView view=new ModelAndView("jspVariabletest");
        List<Employee> empList=new ArrayList<Employee>();
        
        Employee emp=new Employee();
        emp.setAge("27");
        emp.setName("prajith");
        Address add=new Address();
        add.setStreet("Testing");
        add.setCity("Mumbai");
        emp.setAddress(add);
        
        Employee emp2=new Employee();
        emp2.setAge("27");
        emp2.setName("pooja");
        Address add2=new Address();
        add2.setCity("chennai");
        add2.setStreet("2nd street");
        emp2.setAddress(add2);
        
        empList.add(emp);
        empList.add(emp2);
        
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("empList", empList);
        view.addObject("empMap",map);//adding the map object to the request 
        
        ObjectMapper mapper=new ObjectMapper();// jackson lib for converting to json
        String empMapString=mapper.writeValueAsString(map);// json string
        view.addObject("empMapString",empMapString);
        
        return view;
    }
}
 

  


Now simple jsp to convert java object to JavaScript. I have kept actual java Object and json Object to show the difference how it assigns to the JavaScript variable.

jspVariabletest.jsp


<%@ 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">
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<script>
var empMap="${empMap}";// acutal java object assigning to javascript variable 
var empObj=${empMapString};//actual jsonString assigning to javascript variable

</script>
<c:forEach items="${empMap}" var="entry">
    Key = ${entry.key}, value = ${entry.value}<br>
</c:forEach>
</body>
</html> 








Now i have debugged the code in google chrome developer tool and attached the screen shot of the two objects we have created and assigned to JavaScript variable.

The java Map object we are getting in string  which i have assigned to empMap variable of javascipt and the json object we are getting as JavaScript object which I have assigned to empObj. Which is ready to use. If we apply the other logic i have got from the other site, it would have took long time to change this simple object to JavaScript object which is not feasible for changing complex object.


No comments:

Post a Comment