Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GWT overlay types, converting to JSON

Tags:

json

gwt

In GWT, what is the best way to convert a JavaScriptObject overlay type into a JSON string?

I currently have

public final String toJSON() {      
    return new JSONObject(this).toString();
}

Which seems to work fine. I would like to know if there are any better approaches.

like image 818
AlexJReid Avatar asked Nov 03 '08 13:11

AlexJReid


2 Answers

I've never actually tried that (only consumed JSON so far, never needed to produce it). This seems to be native browser/javascript functionality.

You could write it as:

public native String toJSON() /*-{
  return this.toString();
}-*/;

They essentially just do the exact same thing and likely result in identical JavaScript output. The optimizing compiler is really amazing.

like image 196
Mark Renouf Avatar answered Nov 02 '22 12:11

Mark Renouf


we have a JSNI method like that, but use douglas crockfords JSON library (in case the browser doesn't supply one natively):

https://github.com/douglascrockford/JSON-js

public native String stringify() /*-{
  return JSON.stringify();
}-*/;

whats nice is that stringify can take parameters to pretty-print the output with a specified indentation... among other things

like image 34
Nick Franceschina Avatar answered Nov 02 '22 13:11

Nick Franceschina