开发者

How to parse complex json in GWT?

I know how to parse simple json, but dont know how to parse a more complex json (array contains another array).

example json string: [{"linkID":"101030","connectingPoints":[[37.7888, -122.388], [37.803918106204456, -122.36559391021729], [37.8107, -122.364]]},{"linkID":"101040","connectingPoints":null}]

My jsni:

public class LinkDefinition extends JavaScriptObject
{
    protected LinkDefinition()
    {
    }

    public final native String getLinkID()
    /*-{
        return this.linkID;
    }-*/;

    public final native JsArray<LatLon> getConnectingPoints()
    /*-{
        return this.connectingPoints;
    }-*/;
}

and

public class LatLon extends JavaScriptObject
{
    public final int LAT = 0;
    public final int LON = 1;

    protected LatLon()
    {   
    }

    public final native double getLat()
    /*-{
        return this[LAT}; // edited
    }-*/;

    public final native double getLon()
    /*-{
        return this[LON]; // edited
   开发者_如何学Go }-*/;
}

Now I got the error message

[ERROR] [MyProj] - Line x: Instance fields cannot be used in subclasses of JavaScriptObject


You can read this doc about JavaScriptObject restrictions... http://google-web-toolkit.googlecode.com/svn/trunk/distro-source/core/src/doc/helpInfo/jsoRestrictions.html

Otherwise, everything that Thomas said. The main error is public final int fiels (change them to static exactly as he suggested)


The error comes from the public final int fields in LatLon. Change them to static to turn them into constants and fix the error.

You also have an issue in your code in that getLat and getLon return this instead of this[0] and this[1] (or this[@packageOf.LatLon::LAT] and this[@packageOf.LatLon::LON])


You can also parse JSON string and access fields instead of using overlays. You can do it with com.google.gwt.json.client.JSONParser. It has two methods

  1. parseLenient(), which you should only use if you are sure there won't be any JS code injected (eg. comes from your server)
  2. parseStrict() which is slower, but is resistant to code injection
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜