janetsmith
janetsmith

Reputation: 8722

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
    }-*/;
}

Now I got the error message

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

Upvotes: 0

Views: 1092

Answers (3)

okrasz
okrasz

Reputation: 3976

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

Upvotes: 0

Pantelis
Pantelis

Reputation: 6136

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)

Upvotes: 2

Thomas Broyer
Thomas Broyer

Reputation: 64541

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

Upvotes: 1

Related Questions