I'm trying, for the first time, to parse json in gwt and it's not working. Since I'm a newbie this might be some obvious stupid mistake. The array is not retrieved correctly.
This is the piece of code on which I'm debugging:
String json = "{\"lokacije\":[{\"sifraLokacije\":1,\"nazivLokacije\":\"Policijska stanica\",\"brojDokumenata\":70}],\"status\":1}";
LocationsResponse locationsResponse = createLocationsResponse("("+json+")");
// this is ok, status is 1
int status = locationsResponse.getStatus();
// length of this array is 0 and you can see from json that it has one element (the same if it has more)
int brojLokacija = locationsResponse.getLokacije().length();
...
private final native LocationsResponse createLocationsResponse(String json) /*-{
return eval(json);
}-*/;
LocationsResponse class:
public class LocationsResponse extends JavaScriptObject {
protected LocationsResponse() {}
public final native int getStatus() /*-{ return this.status; }-*/;
public final native JsArray<JSOLokacija> getLokacije() /*-{ this.lokacije; }-*/;
}
JSOLokacija class:
public class JSOLokacija extends JavaScriptObject {
protected JSOLokacija() {} ;
public final native int getSifraLokacije() /*-{ this.sifraLokacije; }-*/;
public final native String getNazivLokacije() /*-{ this.nazivLokacije; }-*/;
public final native int getBrojDokumenata() /*-{ this.brojDokumenata; }-*/;
}
Second edit: Wow, I'm just useless today. My first answer returned JSONValue, which is pretty annoying if you want to work with a JSO.
Edit: Aaand just noticed your comment that you fixed it... Still, using the provided tools will tend to help prevent you from getting into annoying situations like this.
Here is another tool you should be aware of, esp if you are after using JSON, and not just objects from JS: AutoBeans (http://code.google.com/p/google-web-toolkit/wiki/AutoBean) - with these, you don't need to write out the JSNI code, just define the properties you expect to have, and it will work out all the wrapper code.
First, mostly useless answer:
eval
doesn't work like that - it is meant to run JS, not turn JSON into data, and a json expression (also a js expression) isn't a legal statement in Javascript. Adding the "(" and ")" around the content is why it is working at all, but this is somewhat risky - usually it is better to trust the browser to do it right if possible:
Use JSONParser.parseStrict
(or parseLenient
if you expect parsing errors, but are absolutely certain that no possible attacks could be coming from there - this will end up calling eval for you, but this way you dont have to maintain it) instead to make sure the content is safe, and to parse it to js correctly. To turn this into a JSO then, you call .isObject().getJavaScriptObject()
on the result of the parse method, which you then have to .cast() to the right value.