Swap Methods
Various methods can be defined on a class directly to affect how it gets serialized.
This can often be simpler than using PojoSwaps
.
Objects serialized as Strings
can be parsed back into their original objects by
implementing one of the following methods on the class:
public static T fromString(String)
method.
valueOf(String)
parse(String)
parseString(String)
forName(String)
forString(String)
public T(String)
constructor.
Note that these methods cover conversion from several built-in Java types, meaning the parsers can automatically construct these objects from strings:
fromString(String)
- {@link java.util.UUID}
valueOf(String)
- {@link java.lang.Boolean}, {@link java.lang.Byte},
{@link java.lang.Double}, {@link java.lang.Float},
{@link java.lang.Integer}, {@link java.lang.Long}, {@link java.lang.Short}, {@link java.sql.Date},
{@link java.sql.Time}, {@link java.sql.Timestamp}
parse(String)
- {@link java.text.DateFormat}, {@link java.text.MessageFormat},
{@link java.text.NumberFormat}, {@link java.util.Date}, {@link java.util.logging.Level}
parseString(String)
- {@link javax.xml.bind.DatatypeConverter}
forName(String)
- {@link java.lang.Class}
If you want to force a bean-like class to be serialized as a string, you can use the
{@link oaj.annotation.BeanIgnore @BeanIgnore} annotation on the class to force it to be
serialized to a string using the toString()
method.
Serializing to other intermediate objects can be accomplished by defining a swap method directly on the class:
public X swap(BeanSession)
method, where X
is any serializable
object.
The BeanSession
parameter allows you access to various information about the current
serialization session.
For example, you could provide customized results based on the media type being produced
({@link oaj.BeanSession#getMediaType()}).
The following example shows how an HTML5 form template object can be created that gets serialized as a populated HTML5 {@link oaj.dto.html5.Form} bean.
Swapped objects can be converted back into their original form by the parsers by specifying one of the following methods:
public static T unswap(BeanSession, X)
method where X
is the
swap class type.
public T(X)
constructor where X
is the swap class type.
The following shows how our form template class can be modified to allow the parsers to reconstruct our original object: