i’m trying to parse JSON coming from a flow in my gwt 2.0 application.
What is the best way ? Should I use javascriptobject ? JSonParser ? I’m lost with what I’m founding on the web because there’s never the gwt version.
String text = "{\"item\":[{\"Id\":\"1\",\"Name\":\"Bob\"},{\"Id\":\"2\",\"Name\":\"John\"},{\"Id\":\"3\",\"Name\":\"Bill\"}]}";
How can I play with my list of items ?
Thanks in advance for any help
The answer depends on how much you trust that JSON 🙂 Sure, it might be coming from your application, but if insert some untrusted user input, you are facing a possible security hole.
So:
eval()function which means (at least) two things: JSON parsing will be extremely fast (it uses browsers native code for that) and will be possibly insecure. Google for more info about JSON related security issues.JSONParsercan also parse JSON viaeval(), when you invoke itsparseLenient(String jsonString)method, but it’s definitely less attractive than JSO.JSONParserviaJSONParser.parseStrict(String jsonString)(available in GWT >=2.1) – you’ll have to write more code that way, but you can be sure that the input is properly handled. You might also look into integrating the “official” JSON parser from json.org with JSO – write a JSNI function that returns the parsed object and cast it to your JSO – in theory it should work 😉 (that’s what GWT does internally with JSOs, at least from what I understood)As for accessing lists in JSON, there are appropriate classes for that:
JsArray(generic, for lists of other JSOs),JsArrayString, etc. If you look at their implementation, they are just JSNI wrappers around the native JS arrays, so they are very fast (but limited, for some reason).Edit in response to Tim’s comment:
I wrote a simple abstract class that helps to minimize the boilerplate code, when dealing with JSOs and JSON:
Then you write your actual JSO as such:
And finally in your code:
Your JSON looks like this (courtesy of JSONLint, a great JSON validator):
So, I’d write a JSO that describes the items of that list:
Then, in your code you call
TestResponse.getTestList(someJsonString)and play around with theJsArrayyou get (theTestResponses it contains are created automagically). Cool, eh? 😉 It might be a bit confusing at first, but believe me, it will make sense once you start using it and it’s a lot easier than parsing viaJSONParser>_>