我正在开发一个接收JSON字符串的GWT应用程序,而且我很难找到每个对象的值.我正在尝试将传入的JSON字符串传输到对象数组中.
这是JSON(来自Firebug响应选项卡),"d"是.NET的东西(Web Service Being Consumed是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"
}
]
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试将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);
Run Code Online (Sandbox Code Playgroud)
}
我想我已经将问题缩小到JSONArray创建实例的位置.我是如何尝试这样做的,这有什么明显的错误,因为我在错误信息方面得不到多少帮助?
Igo*_*mer 19
回应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!
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,在使用时JSONParser你必须/应该非常谨慎 - 这就是重点,对吗?要解析不安全的JSON(否则,就像我在评论中建议的那样,你应该使用JavaScript Overlay Types).你得到一个JSONValue,检查它是否真的是你认为它应该是,a JSONObject,你得到它JSONObject,检查它是否有"xyz"键,你得到一个JSONValue,冲洗并重复.不是最有趣的工作,但至少它比仅仅调用eval()整个JSON 更安全:)
注意:正如Jason指出的,在GWT 2.1之前,内部JSONParser使用eval()(它只有一个parse()方法 - GWT 2.0 javadocs vs GWT 2.1).在GWT 2.1中,parse()被弃用了,引入了另外两种方法 - parseLenient()(eval()内部使用)和parseStrict()(安全方法).如果你真的必须使用JSONParser,那么我建议升级到GWT 2.1 M2,因为否则你也可以使用JSO.作为JSONParser不受信任源的替代方法,您可以尝试通过JSNI将json2.js集成为JSON解析器.
PS:cinqoTimo,JSONArray jsonValue = JSONParser.parse(incomingJsonRespone);显然不起作用,因为JSONParser.parse有一个返回类型JSONValue,不是JSONArray- 你的IDE(Eclipse +谷歌插件?)没有警告你?或者至少是编译器.