Converting GWT Java objects to JavaScript
Converting between native JavaScript objects and GWT Java objects is something the Smart GWT
framework needs to do very frequently (see also
JavaScriptToJavaConversion
).
It is less common for application code to do such conversions, but the need can arise. The
JSOHelper
class contains many utility methods for
sophisticated conversion from GWT Java objects to native JS objects. This article describes
the common rules used when such conversions are run.
- Conversion is recursive; nested Java Maps, Collections and arrays will have their members converted as well
- Circular references (where an object is referred to by its own children, grandchildren, etc) are not
tolerated. If you try to convert a Java object that contains circular references, your program will crash
- null is returned as null
- Strings are converted to JavaScript Strings
- Booleans are converted to JavaScript booleans
- Numeric data types - Integer, Long, Float, Double and all other Number subclasses - are converted to JavaScript
Number
s. Note that it is not possible to accurately represent values with an
absolute value greater than 9,007,199,254,740,992 in a JavaScript Number
(some people find it
easier to remember "15 decimal digits", from the rounded-down value 999,999,999,999,999). This is
not a problem for most Java numeric types, but Java Long
s can accurately represent values
larger than this; converting such a large value to a JavaScript Number
introduces a loss
of precision in the least significant digits. For example, the Java value
Long.MAX_VALUE
is 9223372036854775807. This value will be represented as 9223372036854776000
when converted to a JavaScript Number
ValueEnum
s are converted to the string representation
obtained by calling their getValue()
method
java.util.Date
s (and subclasses) are converted as JavaScript Date
s
RelativeDate
s are converted to the string representation
obtained by calling their getValue()
method
- Java arrays are converted to JavaScript arrays, with members recursively converted to the
equivalent JavaScript type using the rules described in this article
- Java Collections (Lists and Sets) and Iterators are converted to JavaScript arrays, with members
recursively converted to the equivalent JavaScript object using the rules described in this article
- Java Maps are converted to JavaScript Objects with each key mapped to a property on the object.
Property values are recursively converted to the equivalent JavaScript object using the rules described
in this article
Other Java Objects, including POJOs, instances of Record
and its subclasses,
and instances of Canvas
and FormItem
are stored on the underlying data object unconverted. Developers can retrieve such values via
DataClass.getAttributeAsObject(String)
.