One-way Swaps
In the previous sections, we defined two-way swaps, meaning swaps where the original objects could be reconstructing during parsing. However, there are certain kinds of objects that we may want to support for serializing but that are not possible to reconstruct during parsing. For these, we can use one-way object swaps.
See the guide: Serialize a type Juneau doesn't know
A one-way swap is simply an object transform that only implements the swap() method.
The unswap() method is simply left unimplemented.
As of 10.0.0, Iterator, Iterable, Stream, and Enumeration types are serialized natively by all serializers
without needing any swap. The IteratorSwap and EnumerationSwap classes have been removed.
See Release 10.0.0 for details.
An example of a one-way swap would be one that converts a Thread to a simple map containing its name and state.
It can make sense to serialize a Thread for diagnostics but it is not possible to reconstruct a Thread during parsing.
public class ThreadSwap extends ObjectSwap<Thread, JsonMap> {
@Override /* ObjectSwap */
public JsonMap swap(MarshallingSession session, Thread thread) {
return JsonMap.of("name", thread.getName(), "state", thread.getState().name());
}
}
Here is an example of our one-way swap being used. Note that trying to parse the original object will cause a ParseException to be thrown.
// Create a JSON serializer that can serialize Threads.
WriterSerializer serializer = Json5Serializer.create().swaps(ThreadSwap.class).build();
// Serialize the current thread.
String json = serializer.write(Thread.currentThread()); // Produces "{name:'main',state:'RUNNABLE'}"