Ads Inside Post

Search in This Blog

Simple JSON in JSP

Simple JSON in JSP

JSON is very lightweight than XML.Here is the simple example of JSON with java.
I have used "json-simple-1.1.1.jar" , so you need to download it.

index.jsp
---------------------
<%@ page import="org.json.JSONObject"%>
<%@ page import="javax.json.Json"%>
<%@ page import="java.io.PrintWriter"%>
<script src="jquery-1.10.2.js" type="text/javascript"></script>
<input type="button" value="send" onclick="dook();"/>
<script>
function dook() {
    var datas = ({"msg":'Test Message'});
    var jsonobj=JSON.stringify(datas);
    $.ajax({
        data: {para:jsonobj},
        dataType: 'json',
        url: 'newjsp.jsp',
        type: 'POST',
        success: function(ans){
            alert(ans.res);    
        },
        error: function() {
            alert('Ajax readyState: '+xhr.readyState+'\nstatus: '+xhr.status + ' ' + err);
        }
    });
}
</script>


newjsp.jsp
-------------------
<%@ page import="java.io.PrintWriter"%>
<%@ page import="org.json.simple.JSONObject"%>
<%@ page import="org.json.simple.JSONValue"%>
<%
request.setCharacterEncoding("utf8");
response.setContentType("application/json");
PrintWriter outt = response.getWriter();
JSONObject jsonObj = (JSONObject) JSONValue.parse(request.getParameter("para"));
System.out.println(jsonObj.get("msg"));
JSONObject obj = new JSONObject();
obj.put("res", "hello...");
out.print(obj);
%>