答案取决于您对 JSON 的信任程度:) 当然,它可能来自您的应用程序,但如果插入一些不受信任的用户输入,您可能会面临安全漏洞。
所以:
至于访问 JSON 中的列表,有相应的类:JsArray(通用,用于其他 JSO 的列表)、JsArrayString 等。如果您查看它们的实现,它们只是围绕原生 JS 数组,因此它们非常快(但由于某种原因受到限制)。
编辑以回应 Tim 的评论:
在处理 JSO 和 JSON 时,我编写了一个简单的抽象类,有助于最大限度地减少样板代码:
import com.google.gwt.core.client.JavaScriptObject;
public abstract class BaseResponse extends JavaScriptObject {
// You can add some static fields here, like status codes, etc.
/**
* Required by {@link JavaScriptObject}
*/
protected BaseResponse() { }
/**
* Uses <code>eval</code> to parse a JSON response from the server
*
* @param responseString the raw string containing the JSON repsonse
* @return an JavaScriptObject, already cast to an appropriate type
*/
public static final native <T extends BaseResponse> T getResponse(String responseString) /*-{
// You should be able to use a safe parser here
// (like the one from json.org)
return eval('(' + responseString + ')');
}-*/;
}
然后你这样写你的实际 JSO:
import com.example.client.model.User;
public class LoginResponse extends BaseResponse {
protected LoginResponse() { }
public final native String getToken() /*-{
return this.t;
}-*/;
public final native int getId() /*-{
return parseInt(this.u[0]);
}-*/;
// ...
// Helper method for converting this JSO to a POJO
public final User getUser() {
return new User(getLogin(), getName(), getLastName());
}
}
最后在你的代码中:
// response.getText() contains the JSON string
LoginResponse loginResponse = LoginResponse.getResponse(response.getText());
// ^ no need for a cast \o/
您的 JSON 如下所示(感谢 JSONLint,一个出色的 JSON 验证器):
{
"item": [
{
"Id": "1",
"Name": "Bob"
},
{
"Id": "2",
"Name": "John"
},
{
"Id": "3",
"Name": "Bill"
}
]
}
所以,我会编写一个 JSO 来描述该列表中的项目:
public class TestResponse extends BaseResponse {
protected TestResponse() { }
public final native String getId() /*-{
return this.Id;
}-*/;
public final native String getName() /*-{
return this.Name;
}-*/;
// Static helper for returning just the list
// Code untested but you should get the idea ;)
public static final native JsArray<TestResponse> getTestList(String json) /*-{
var stuff = eval('(' + json + ')');
return stuff.item;
}-*/;
}
然后,在你的代码中调用TestResponse.getTestList(someJsonString) 并使用你得到的JsArray(它包含的TestResponses 是自动创建的)。酷,嗯? ;) 一开始可能有点令人困惑,但相信我,一旦你开始使用它就会变得有意义,而且它比通过 JSONParser 解析要容易得多 >_>