使用 gwt 2.0 解析 json [英] Parse json with gwt 2.0

查看:33
本文介绍了使用 gwt 2.0 解析 json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析来自我的 gwt 2.0 应用程序中的流的 JSON.

i'm trying to parse JSON coming from a flow in my gwt 2.0 application.

最好的方法是什么?我应该使用 javascriptobject 吗?JSonParser ?我对我在网络上创建的东西迷失了方向,因为从来没有 gwt 版本.

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 ?

在此先感谢您的帮助

推荐答案

答案取决于您对 JSON 的信任程度 :) 当然,它可能来自您的应用程序,但是如果插入一些不受信任的用户输入,您将面临一个可能的安全漏洞.

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.

所以:

  • 对于来自可信来源的 JSON,我使用 JavaScript叠加类型.他们使 JSON 与 GWT 无缝集成,我绝对推荐这种方法.但是,在内部,这会调用 eval() 函数,这意味着(至少)两件事:JSON 解析将非常快(它为此使用浏览器本机代码)并且可能不安全.有关 JSON 相关安全问题的更多信息,请访问 Google.JSONParser 还可以通过 eval() 解析 JSON,当您调用它的 parseLenient(String jsonString) 方法,但是它绝对没有 JSO 吸引人.
  • 对于不受信任的来源/输入,您应该使用 JSONParser 通过 JSONParser.parseStrict(String jsonString) (在 GWT >=2.1 中可用) - 您必须以这种方式编写更多代码,但您可以确保正确处理输入.您还可以考虑将官方"来自 json.org 的 JSON 解析器与 JSO 集成 - 编写一个JSNI 函数返回解析的对象并将其转换为您的 JSO - 在理论上它应该工作;)(这就是 GWT 在内部对 JSO 所做的,至少从我的理解来看)
  • for JSONs from trusted sources, I use JavaScript Overlay Types. They make integrating JSON with GWT seamless and I'd definitely recommend this approach. However, internally, this calls the 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. JSONParser can also parse JSON via eval(), when you invoke its parseLenient(String jsonString) method, but it's definitely less attractive than JSO.
  • for untrusted sources/input, you should use JSONParser via JSONParser.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)

至于访问 JSON 中的列表,有相应的类:JsArray(通用,用于其他 JSO 的列表),JsArrayString 等.如果你看看它们的实现,它们只是原生 JS 数组的 JSNI 包装器,因此它们非常快(但由于某种原因受到限制).

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

根据 Tim 的评论进行

在处理 JSO 和 JSON 时,我编写了一个简单的抽象类,有助于最小化样板代码:

I wrote a simple abstract class that helps to minimize the boilerplate code, when dealing with JSOs and 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:

Then you write your actual JSO as such:

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 验证器):

Your JSON looks like this (courtesy of JSONLint, a great JSON validator):

{
    "item": [
        {
            "Id": "1",
            "Name": "Bob"
        },
        {
            "Id": "2",
            "Name": "John"
        },
        {
            "Id": "3",
            "Name": "Bill"
        }
    ]
}

因此,我将编写一个 JSO 来描述该列表中的项目:

So, I'd write a JSO that describes the items of that list:

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(它包含的 TestResponse 是自动创建的).酷,嗯?;) 一开始可能有点令人困惑,但相信我,一旦你开始使用它就会有意义,而且它比通过 JSONParser 解析 容易很多 >_>

Then, in your code you call TestResponse.getTestList(someJsonString) and play around with the JsArray you get (the TestResponses 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 via JSONParser >_>

这篇关于使用 gwt 2.0 解析 json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆