PDA

View Full Version : JSON parsing problem


Anas
12-11-2009, 09:30 AM
Hi,
When executed the below client code,

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>

<html>
<head>

</head>
<script type="text/javascript" src="/JsonSample/jsp/json2.js"></script>
<script type="text/javascript">
function createXMLHttpRequest(){
if( typeof XMLHttpRequest == "undefined" )
XMLHttpRequest = function() {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") }catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") }catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP") }catch(e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP") }catch(e) {}
throw new Error( "This browser does not support XMLHttpRequest." )
};
return new XMLHttpRequest();
}

var AJAX = createXMLHttpRequest();

function handler() {
if(AJAX.readyState == 4 && AJAX.status == 200) {
//var json = eval("(" + AJAX.responseText + ")");
var json = JSON.parse(AJAX.responseText);
alert('Success. Result: name => ' + json.name + ',' + 'balance => ' + json.balance);
}
else if (AJAX.readyState == 4 && AJAX.status != 200) {
alert('Something went wrong...');
}
}

function show(){
AJAX.onreadystatechange = handler;
AJAX.open("GET", "service.jsp");
AJAX.send("");
};

</script>
<body>
<a href="#" onclick="javascript:show();"> Click here to get JSON data from the server side</a>
</html>



I am getting "undefined" for the value json as in "var json = JSON.parse(AJAX.responseText);".
The server side code is as follows:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="net.sf.json.*"%>
<html>
<head>
<title>service</title>

<meta name="GENERATOR" content="Rational Application Developer">
</head>
<body>


<% JSONObject obj=new JSONObject();
obj.put("name","foo"); obj.put("num",new Integer(100));
obj.put("balance",new Double(1000.21));
obj.put("is_vip",new Boolean(true));
obj.put("nickname",null);
out.print(obj);
out.flush(); %>
</body>
</html>


The AJAX.responseText is having the value

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>service</title>
<meta name="GENERATOR" content="Rational Application Developer">
</head>
<body>{"name":"foo","num":100,"balance":1000.21,"is_vip":true}
</body>
</html>

Since json is undefined, i am getting a script error saying "name is null or not an object".
Please help in getting the values server side.

A1ien51
12-11-2009, 12:31 PM
You really need to use code tags when posting code. Without it your post is unreadable.

2nd, you really should use a JavaScript library or look for another way to make an Ajax call. The code you are using is really bad.

3rd,

the problem you have is the page that is being returned should just be the json object. It should not have any html, bead, or body tags. The content type should be text/json

The only thing that should be in your responseText is

{"name":"foo","num":100,"balance":1000.21,"is_vip":true}

You really should be calling a servlet and not a JSP page.

Eric

Anas
12-16-2009, 08:55 AM
Hi,
I sincerely apolozise for the point1 "use code tags when posting code", I am a first timer to forums.
The codepiece which i posted is just a sample for my learning.

I modified the function handler() by including "var json1 = JSON.stringify(AJAX.responseText);" which enables me to get the value for json as in "var json = eval("(" + json1 + ")");".
But now i am getting 'Success. Result: name => undefined,balance => undefined'
I even changed the content type of service.jsp to "text/json".

function handler(){
if(AJAX.readyState == 4 && AJAX.status == 200) {
var json1 = JSON.stringify(AJAX.responseText);
var json = eval("(" + json1 + ")");
alert('Success. Result: name =>undefined, balance => + json.balance);
}
else if (AJAX.readyState == 4 && AJAX.status != 200) {
alert('Something went wrong...');
}
}

Please help to get the value of name and balance?
Your solution is greatly appreciated.


Regards,
anas

rnd me
12-16-2009, 10:36 AM
you would need eval() or JSON.parse(), not JSON.stringify()...


i find jsonp a lot easier to debug than ajax because firebug can show you the part of the script that's causing trouble, often including a line number. the evals are generally harder to debug, which is one reason why eval() is frowned upon.

if you can simply place one word in front of, and parens around the server response, you can get rid of the ajax and json parts and eval() while shortening and simplifying your code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<body>
<script type="text/javascript">

function handler(json) {
alert('Success. Result: name => ' + json.name + ',' + 'balance => ' + json.balance);
}

function show(){ jsGet("service.jsp?cb=handler"); };


function jsGet(turl) {var d=document, xJs = d.createElement("script");
d.getElementsByTagName("head")[0].appendChild(xJs);xJs.src = turl;}
</script>
<a href="#" onclick='javascript:handler({"name":"foo","num":100,"balance":1000.21,"is_vip":true});return false;'> Click here to test JSON callback</a><br />
<a href="#" onclick="javascript:show();return false;"> Click here to get JSON data from the server side</a>
</html>

this demo alerts "Success. Result: name => foo,balance => 1000.21"

you server response could look like this:
handler({"name":"foo","num":100,"balance":1000.21,"is_vip":true})

firebug will let you know a lot more about errors than "something went wrong"...

the response type doesn't matter for jsonp.
service.jsp might look like this:


<%@page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="net.sf.json.*"%>
<%
JSONObject obj=new JSONObject();
obj.put("name","foo"); obj.put("num",new Integer(100));
obj.put("balance",new Double(1000.21));
obj.put("is_vip",new Boolean(true));
obj.put("nickname",null);
out.print( request.getParameter("cb") );
out.print( "(" );
out.print(obj);
out.print( ")" );
out.flush(); %>


i'm not a jsp guy, so this may not work, but something like it will...

Anas
12-17-2009, 08:30 AM
Hi,

Thanks for the suggestion.

The problem is resolved when i removed html tags in service.jsp and simply returned json object.Also removed the line "var json1 = JSON.stringify(AJAX.responseText);
"

Thank you Eric.


Regards,
Anas