GWT: Dealing with incoming JSON string

后端 未结 2 1356
灰色年华
灰色年华 2020-12-28 21:07

I am working on a GWT app that is receiving a JSON string, and I\'m having a hard time getting down to the values of each object. I\'m trying to transfer the incoming JSON s

2条回答
  •  有刺的猬
    2020-12-28 21:47

    In response to RMorrisey's comment:
    Actually, it's more convoluted :/ It would look something like this (code untested, but you should get the general idea):

    JSONValue jsonValue;
    JSONArray jsonArray;
    JSONObject jsonObject;
    JSONString jsonString;
    jsonValue = JSONParser.parseStrict(incomingJsonRespone);
    // parseStrict is available in GWT >=2.1
    // But without it, GWT is just internally calling eval()
    // which is strongly discouraged for untrusted sources
    
    if ((jsonObject = jsonValue.isObject()) == null) {
        Window.alert("Error parsing the JSON");
        // Possibilites: error during download,
        // someone trying to break the application, etc.
    }
    
    jsonValue = jsonObject.get("d"); // Actually, this needs
                                     // a null check too
    if ((jsonArray = jsonValue.isArray()) == null) {
        Window.alert("Error parsing the JSON");
    }
    
    jsonValue = jsonArray.get(0);
    if ((jsonObject = jsonValue.isObject()) == null) {
        Window.alert("Error parsing the JSON");
    }
    
    jsonValue = jsonObject.get("Desc");
    if ((jsonString = jsonValue.isString()) == null) {
        Window.alert("Error parsing the JSON");
    }
    
    Window.alert(jsonString.stringValue()); // Finally!
    

    As you can see, when using JSONParser you have to/should be very cautious - that's the whole point, right? To parse an unsafe JSON (otherwise, like I suggested in the comments, you should go with JavaScript Overlay Types). You get a JSONValue, check if it's really what you think it should be, say, a JSONObject, you get that JSONObject, check if it has the "xyz" key, you get a JSONValue, rinse and repeat. Not the most interesting work, but at least its safer than just calling eval() on the whole JSON :)
    Attention: as Jason pointed out, prior to GWT 2.1, JSONParser used eval() internally (it only had a parse() method - GWT 2.0 javadocs vs GWT 2.1). In GWT 2.1, parse() became deprecated and two more methods were introduced - parseLenient() (uses eval() internally) and parseStrict() (the safe approach). If you really have to use JSONParser, then I'd suggest upgrading to GWT 2.1 M2, because otherwise you might as well use JSOs. As an alternative to JSONParser for untrusted sources, you could try integrating json2.js as a JSON parser via JSNI.

    PS: cinqoTimo, JSONArray jsonValue = JSONParser.parse(incomingJsonRespone); obviously doesn't work because JSONParser.parse has a return type of JSONValue, not JSONArray - didn't your IDE (Eclipse + Google Plugin?) warn you? Or at least the compiler.

提交回复
热议问题