java GWT:处理传入的 JSON 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3490255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 02:02:52  来源:igfitidea点击:

GWT: Dealing with incoming JSON string

javajsongwt

提问by tpow

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 string into an array of objects.

我正在开发一个接收 JSON 字符串的 GWT 应用程序,我很难深入了解每个对象的值。我正在尝试将传入的 JSON 字符串传输到对象数组中。

Here is the JSON (from Firebug response tab), The "d" is a .NET thing (Web Service Being Consumed is C#.

这是 JSON(来自 Firebug 响应选项卡),“d”是 .NET 的东西(正在使用的 Web 服务是 C#。

{
    "d": [
        {
            "__type": "Event",
            "ID": 30,
            "Bin": 1,
            "Date": "\/Date(1281544749000)\/",
            "Desc": "Blue with white stripes.",
            "Category": "1"
        },
        {
            "__type": "Event",
            "ID": 16,
            "Bin": 3,
            "Date": "\/Date(1281636239000)\/",
            "Desc": "Yellow with pink stripes",
            "Category": "1"
        }

    ]
}

I'm trying to parse the JSON into objects, and then insert them into an array. I'm able to use Window.alertand get the entire "d" object to echo. However, when I try to access the elements of the array, GWT debugger just crashes.

我正在尝试将 JSON 解析为对象,然后将它们插入到数组中。我能够使用Window.alert并获得整个“d”对象的回声。但是,当我尝试访问数组元素时,GWT 调试器崩溃了。

//My GWT array to receive JSON Array
ArrayList<Item> itemInfo = new ArrayList<Item>();

//Getting response JSON into something I can work with.(THIS FAILS) 
JSONArray jsonValue = JSONParser.parse(incomingJsonRespone);

//Just trying to verify I'm getting values 
for (int i=0; i<jsonValue.size(); i++) {
    JSONValue jsonItem =  = JsonValue.get(i).getString();
    Window.alert(jsonItem);
    itemInfo.add(jsonItem);

}

}

I think I have narrowed down the problem to where the JSONArrayinstance is being created. Is there something blatantly wrong with how I'm trying to do this, because I'm not getting much help in the way of error messages?

我想我已经将问题缩小到JSONArray创建实例的位置。我尝试这样做的方式是否存在明显错误,因为我在错误消息方面没有得到太多帮助?

回答by Igor Klimer

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):

回应 RMorrisey 的评论:
实际上,它更令人费解:/它看起来像这样(代码未经测试,但您应该了解总体思路):

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 JSONParseryou 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, JSONParserused eval()internally (it only had a parse()method - GWT 2.0javadocs 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 JSONParserfor untrusted sources, you could try integrating json2.js as a JSON parser via JSNI.

如您所见,使用时JSONParser您必须/应该非常谨慎 - 这就是重点,对吗?要解析不安全的 JSON(否则,就像我在评论中建议的那样,您应该使用JavaScript Overlay Types)。你得到 a JSONValue,检查它是否真的是你认为应该是的,比如说, a JSONObject,你得到那个JSONObject,检查它是否有“xyz”键,你得到 a JSONValue,冲洗并重复。不是最有趣的工作,但至少它比仅仅调用eval()整个 JSON更安全:)
注意:正如 Jason 指出的那样,在 GWT 2.1 之前,在内部JSONParser使用eval()(它只有一个parse()方法 - GWT 2.0javadocs vs GWT 2.1)。在 GWT 2.1 中,parse()已被弃用,并引入了另外两种方法 - parseLenient()eval()内部使用)和parseStrict()(安全方法)。如果您真的必须使用JSONParser,那么我建议升级到 GWT 2.1 M2,否则您不妨使用 JSO。作为JSONParser不受信任的来源的替代方案,您可以尝试通过 JSNIjson2.js集成为 JSON 解析器

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

PS:cinqoTimo,JSONArray jsonValue = JSONParser.parse(incomingJsonRespone);显然不起作用,因为JSONParser.parse它的返回类型是JSONValue,不是JSONArray- 你的 IDE(Eclipse + Google 插件?)没有警告过你吗?或者至少是编译器。

回答by RMorrisey

It looks like you don't have an array, but a single root object, whose property called 'd' is an array. I'm not familiar with that specific API, but maybe you can try retrieving a JSONObject or similar instead of an array?

看起来您没有数组,而是一个根对象,其名为 'd' 的属性是一个数组。我不熟悉那个特定的 API,但也许您可以尝试检索 JSONObject 或类似的而不是数组?