views:

224

answers:

2

I am currently trying to pass a generated JSON string to dojo for parsing and am having some issues. The servlet simply writes it as a string as so:

response.getWriter().append("{ \"data\": {");
response.getWriter().append("\"type\": \"facing\",");
response.getWriter().append("\"score\": " + "\"" + score + "\",");
response.getWriter().append("\"count\":" + "\"" + count + "\"" );
response.getWriter().append("}}");

which prints as:

{"data":{"type":"facing","score":"10","count":"24"}}

And the parsing on the dojo end looks as so:

dojo.xhrPost({
    url: url,
    handleAs: "json",
    load: function(data) {
        alert(data);
        /* Parse Not working */
        alert(data.data[0].type);  
    },
    error: function(error) {
        alert("No dice")
    }
});

The main issue is the data.data[0].type is returning nothing but when i print this out as text the json seems to be correctly formatted. Any help with this would be appreciated.

A: 

Self-Solved: Only use the [] operator to dereference values from arrays but if extracting values from object use the dot notation. So to get the type one would simply need to do: data.data.type

Traker
A: 

I strongly recommend using Google Gson to convert maps and/or collections of fullworthy javabeans to JSON and vice versa. You can find here several examples. Learning JSON would also help much.

BalusC