Monday, April 27, 2015

How to convert Java Object in JSON and how to retrieve it at client side

To converting a java object in JSON we need to user some 3rd party API here I’m using “gson.2.2.4.jar” .




Step 1-  Create a JAVA bean class. I’m creating a class as Employee.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.json.conversion

public class Employee {

    private int age;
    private String name;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Step 2 - Create jsp “createJSONObject.jsp” in this jsp create Employee class object and set some of the value to it.

1
2
3
4
5
6
7
8
9
Employee obj1 = new Employee();
    obj1.setAge(10);
    obj1.setName("Ram");
    Employee obj2 = new Employee();
    obj2.setAge(20);
    obj2.setName("Shyam");
    Employee obj3 = new Employee();
    obj3.setAge(30);
    obj3.setName("Mohan");

Step 3 - Add this class to in a ArrayList.

1
2
3
4
 List<Employee> al = new ArrayList<Employee>();
     al.add(obj1);
     al.add(obj2);
     al.add(obj3);

Step 4 - Create Gson class object.

1
Gson gson = new Gson();

Step 5 - Call toJson(Object obj) method by passing the ArrayList object to it.

1
 String json = gson.toJson(al);

This method return a string object. Later we will send this string as a response to client.

Step 6- Write this json string as scriptlet in jsp so this string become a part of response, so we can access this response in javascript and we can display this as per requirement.

1
2
3
4
5
<html>
   <body>
      Your JSON String is as Response : <span id="jsonStr"> <%=json%></span><br>
    </body> 
</html>

Step 7- Get this json string in javascript in form of json object (myObject).

1
2
3
4
5
6
7
8
9
<script type="text/javascript">
    var myObject;
    function getJSONObj() {
        var myJSONtext = document.getElementById("jsonStr").innerHTML;
  //this is used for converting the java response text (string) into json object
        myObject = eval('(' + myJSONtext + ')');
        document.getElementById("jsonObj").innerHTML = myObject;
    }
</script>

Step 8- Display this json object (myObject) as string in the page using javascript by calling getJSONSTR() method.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function getJSONSTR() {
 var counter = 0;
 var loop = 0;
 for (i in myObject)
 {
  loop++;
  var oldDivId;
  if (counter == 0) {
   oldDivId = document.getElementById("J");
   counter++;
  }
  else {
   oldDivId = document.getElementById("jsonstrname" + (loop - 1));
  }
  var age = myObject[i].age;
  var name = myObject[i].name;
  var spanNameTitle = document.createElement("div");
  spanNameTitle.setAttribute("id", "jsonstrname" + loop);
  var nameTitle = document.createTextNode(" Name : " + name + " Age : " + age);
  spanNameTitle.appendChild(nameTitle);
  oldDivId.appendChild(spanNameTitle);
  //document.getElementById('jsonstrname'+i).innerHTML = name;
  //document.getElementById("jsonstrage"+I).innerHTML = age;
 }
}

Example :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ page import="com.google.gson.Gson" %>
<%@ page import="com.json.conversion.Employee" %>
<%@ page import="java.util.ArrayList" %>
<%
    Employee obj1 = new Employee();
    obj1.setAge(10);
    obj1.setName("Ram");
    Employee obj2 = new Employee();
    obj2.setAge(20);
    obj2.setName("Shyam");
    Employee obj3 = new Employee();
    obj3.setAge(30);
    obj3.setName("Mohan");

    List<Employee> al = new ArrayList<Employee>();
    al.add(obj1);
    al.add(obj2);
    al.add(obj3);

    Gson gson = new Gson();
    String json = gson.toJson(al);
%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>json creation</title>
        <script type="text/javascript">
            var myObject;
            function getJSONObj() {
                var myJSONtext = document.getElementById("jsonStr").innerHTML;
                myObject = eval('(' + myJSONtext + ')');//this is used for converting the java response text (string) into json object
                document.getElementById("jsonObj").innerHTML = myObject;
            }
            function getJSONSTR() {
                var counter = 0;
                var loop = 0;
                for (i in myObject)
                {
                    loop++;
                    var oldDivId;
                    if (counter == 0) {
                        oldDivId = document.getElementById("J");
                        counter++;
                    }
                    else {
                        oldDivId = document.getElementById("jsonstrname" + (loop - 1));
                    }
                    var age = myObject[i].age;
                    var name = myObject[i].name;
                    var spanNameTitle = document.createElement("div");
                    spanNameTitle.setAttribute("id", "jsonstrname" + loop);
                    var nameTitle = document.createTextNode(" Name : " + name + " Age : " + age);
                    spanNameTitle.appendChild(nameTitle);
                    oldDivId.appendChild(spanNameTitle);
                    //document.getElementById('jsonstrname'+i).innerHTML = name;
                    //document.getElementById("jsonstrage"+I).innerHTML = age;
                }
            }
        </script>
    </head>
    <body>
        Your JSON String is as Response : <span id="jsonStr"> <%=json%></span><br>
        <button id="jobj" onclick="getJSONObj();">Click here to get JSON object from response text : </button><span id="jsonObj"></span><br>
        <button id="jstr" onclick="getJSONSTR();">Click here to get JSON String from Json object : </button><br>
        <div id="J"></div>
    </body>
</html>

NOTE: use “gson.2.2.4.jar” for this in classpath.

No comments :

Post a Comment