Converting raw JSON to a JSONObject / JSONValue

486 views
Skip to first unread message

Alexander Orlov

unread,
Aug 3, 2011, 10:43:28 AM8/3/11
to google-we...@googlegroups.com
The JSONObject takes only JavaScriptObject as its constructor parameter. JavaScriptObject can be returned only by a JSNI function which I wrote:

    public static native JavaScriptObject parseJson(String jsonStr) /*-{
        return eval(jsonStr);
    }-*/;

but when I do 

String json = "{\"userId\" : \"123\", \"sessionId\" : \"456\"}";
JavaScriptObject javaScriptObject = parseJson(json);


I get

ERROR: Uncaught exception escaped. com.google.gwt.core.client.JavaScriptException: (SyntaxError): Unexpected token : 

-Alex

kim young ill

unread,
Aug 3, 2011, 10:48:52 AM8/3/11
to google-we...@googlegroups.com
try this :

return eval('(' + json + ')');

--
You received this message because you are subscribed to the Google Groups "Google Web Toolkit" group.
To view this discussion on the web visit https://groups.google.com/d/msg/google-web-toolkit/-/Z8Uk3YifLLYJ.
To post to this group, send email to google-we...@googlegroups.com.
To unsubscribe from this group, send email to google-web-tool...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/google-web-toolkit?hl=en.

Alexander Orlov

unread,
Aug 3, 2011, 11:04:35 AM8/3/11
to google-we...@googlegroups.com
Thx!

GWT has a pretty idiosyncratic style!

Btw, were my assumptions how to construct a JSONObject right?

-Alex

Jeffrey Chimene

unread,
Aug 3, 2011, 11:46:35 AM8/3/11
to google-we...@googlegroups.com
On 8/3/2011 8:04 AM, Alexander Orlov wrote:
> Thx!
>
> GWT has a pretty idiosyncratic style!

It's not up to GWT, it's up to the browser to evaluate the string. Take
a look at the source code.


>
> Btw, were my assumptions how to construct a JSONObject right?

Sort of.

The JSON spec indicates that you don't quote numbers, OTOH, your
application may warrant those quotes.

Other points:
o You want to use a JavaScript Object as the destination of the parse
object. Here I deliberately use saveEval because I trust the source of
the string.
JSObject = JsonUtils.safeEval(source);

where JSOBject is a class that extends JavaScriptObject and optionally
implements an interface. Using the interface allows you to mock the JSO.

o You want to use the JSObject as the source of the associated string.
The round trip should be idempotent.

@Override
public final String export() {
return new JSONObject(this).toString();
}

o example:
"{\"activityName\":\"L\", \"id\":12, \"predecessorList\":[11,10],
\"likely\":0, \"worst\":0, \"best\":0}"

Reply all
Reply to author
Forward
0 new messages