public interface IToJSON | Modifier and Type | Method and Description |
|---|---|
void | toJSON(java.io.Writer out, JSTranslater jsTrans) Translate this object to executable JavaScript for transport to the browser. |
void toJSON(java.io.Writer out,
JSTranslater jsTrans)
throws UnconvertableException,
java.io.IOException This example shows a simple way to customize Bean translation by implementing the IToJSON interface.
class MyBean implements IToJSON {
public void toJSON (Writer out, JSTranslater jsTrans) {
try {
Map beanProps = DataTools.getProperties(this);
// here, remove any properties you don't want to send
// (or add or modify any others)
jsTrans.toJS(beanProps, out);
} catch (Exception ignored) {}
}
}
In this example we use DataTools.getProperties() to get all of the Bean's public properties as a Map. This Map can be modified arbitrarily, then the JSTranslater is invoked to transform the Map to a JavaScript Object. The same approach can be used externally to an object if you can't add the IToJSON interface.
Note that this example reused the JSTranslater instance passed as a parameter - you should do this, rather than retrieving a new JSTranslater, because it preserves automatic recursion detection built into the JSTranslater class.
As an alternative to implementing IToJSON, you can wrap objects in a JSONFilter before they are passed to the JSTranlater class.
out - Write your javascript translation of this object to this writer.jsTrans - The calling JSTranslater instanceUnconvertableExceptionjava.io.IOExceptionJSTranslater, JSONFilter, com.isomorphic.util.DataTools#getProperties(Map)