While writing a REST service (in JAX-RS implementation), I needed to create and modify resources using JSON as the exchange format. The client-side is written in GWT. In GWT when you want to convert a string to a Javascript object, you can use eval and it’s done.
But what about serializing objects into strings? Now supposing you’re sending data from a FormHandler, in the onSubmit method, you may want to set the values in the Javascript object and later send it as a string with RequestBuilder.sendRequest. GWT-Ext provides tools for the task, but maybe you’re not using them, so your question at this point would be: must I code a JSON tokenizer in Java for this? (yeah, you’re org.json library won’t work)
No, not at all, since you can use any external JS library from GWT. So go ahead and grab a normal Javascript to do the job, in example, Json2.js. Put the file in a directory reachable by the webrowser and load it with a script tag. The last step is writing an interface for your java code:
import com.google.gwt.core.client.JavaScriptObject;
public class JSON {
protected JSON() {}
public static final native String encode(JavaScriptObject object) /*-{
/** if you use a different library, check the method beneath **/
return $wnd.JSON.stringify(object);
}-*/;
public static final native <T> T decode(String json) /*-{
return eval('('+json+')');
}-*/;
}
When you want to refer to an external Javascript object, you must prefix the access to the object by $wnd. This way you tell GWT that your object is located in Window. Anyway, if you forgot to add it you’d have a compilation error, so you’d spotted it quickly. You have more information about the JNSI interface in this page.
Note: In the decode method, there’s a generic been used so the compiler can guess the type of the left side when you do an assignation. So take care to which type you’re doing the assignation before you get a conflict type error.