GWT: How to implement JSON.stringify(…)
by admin on Jun.01, 2023, under News
The Google Web Toolkit (GWT) is a Java-based framework that allows developers to write client-side web applications using Java, which is then compiled into optimized JavaScript that can run on any browser. The JavaScript Native Interface (JSNI) is a feature of GWT that provides a way to integrate Java code with JavaScript code and browser APIs.
JSNI bindings allow Java code to interact with JavaScript code in two main ways: calling JavaScript functions from Java, and exposing Java methods to be called from JavaScript. To call a JavaScript function from Java, the JSNI syntax is used to create a JavaScript method reference, which can then be invoked from Java code. For example:
native void alert(String message) /*-{ $wnd.alert(message); }-*/;
In this example, the alert() function is a JavaScript function that displays a message in an alert dialog box. The native keyword indicates that the method is implemented in JavaScript, and the JSNI syntax is used to wrap the JavaScript code in a Java method.
We can convert a JavaScriptObject (GWT) to a JSON string using the very same approach:
private static native String convertToJsonString(JavaScriptObject jso) /*-{ return JSON.stringify(jso); }-*/;
This way we can use the JS logic in our GWT code.
Built-in method
Another method would be to use GWT’s built in JsonUtils (com.google.gwt.core.client) which takes a JavaScriptObject parameter:
JavaScriptObject someobject = ...; JsonUtils.stringify(someobject);