GWT: Unterminated string constant

This is another one of those GWT “gotchas” I came across in Internet Explorer.

I have a JSON object with a field that’s chocked full o’ chars (its a big string 🙂 ) This field is displaying descriptive information on the page in every browser BUT IE (go figure).

When debugging, I got this little bugger:

” com.google.gwt.core.client.JavaScriptException: (SyntaxError): Unterminated string constant number: -2146827273 “

Well that’s helpful! So – I snagged the JSON and loaded it up in the first online JSON parser google gave me. Everything looked fine. Ugh! No errors, everything is hunky dory, but in IE, well…

After a long battle with the browsers and looking at the underlying utility class I was using, I saw that the method I was calling was using the native eval().

The method looked a little something like this:

private static native JavaScriptObject evaluate( String json )/*-{
     return eval("(" + json+ ")");
}-*/;

Aha! – this is where the problem was. Turns out that the String being passed (the JSON object) who’s very descriptive field was chocked full o chars contained some chars that IE wasn’t too happy about.

New line chars! It turns out that if you have any”\r\n” in your JSON, IE tends to get a bit angry and call it quits when eval’ing.

The solution? Well – I threw in some logic to take care of formatting the String for IE. I put the format in its own method in case I have to modify the String in any other way down the road.

Once I popped in the below, everything seemed to work AOK!

public static JavaScriptObject evaluate(String json){
     String formattedJson = formatForCrossBrowserCompatibility(json);
     return evaluateFrom(formattedJson);
}

private static String formatForCrossBrowserCompatibility(String json){
     String formattedJson = json.replace( "\r\n", "\\r\\n" );
     return formattedJson.trim();
}

private static native JavaScriptObject evaluateFrom( String json)/*-{
     return eval("(" + json+ ")");
}-*/;

Leave a comment

Filed under Java

Leave a comment