One-way PojoSwaps

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 POJOs 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.

A one-way POJO swap is simply an object transform that only implements the {@code swap()} method. The {@code unswap()} method is simply left unimplemented.

An example of a one-way swaps would be one that allows {@code Iterators} to be serialized as JSON arrays. It can make sense to be able to render {@code Iterators} as arrays, but in general it's not possible to reconstruct an {@code Iterator} during parsing.

public class IteratorSwap extends PojoSwap<Iterator,List> { @Override /* PojoSwap */ public List swap(Iterator o) { List l = new LinkedList(); while (o.hasNext()) l.add(o.next()); return l; } }

Here is an example of our one-way swap being used. Note that trying to parse the original object will cause a {@link oaj.parser.ParseException} to be thrown.

// Create a JSON serializer that can serialize Iterators. WriterSerializer s = JsonSerializer.create().simple().pojoSwaps(IteratorSwap.class).build(); // Construct an iterator we want to serialize. Iterator i = new ObjectList(1,2,3).iterator(); // Serialize our Iterator String json = s.serialize(i); // Produces "[1,2,3]" // Try to parse it. ReaderParser p = JsonParser.create().pojoSwaps(IteratorSwap.class).build(); i = p.parse(s, Iterator.class); // Throws ParseException!!!