{title:'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.

A one-way 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 ObjectSwap<Iterator,List> { | @Override /* ObjectSwap */ | public List swap(Iterator iterator) { | List list = new LinkedList(); | while (iterator.hasNext()) | list.add(iterator.next()); | return list; | } | }

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 serializer = JsonSerializer. create().simple().swaps(IteratorSwap. class).build(); | | // Construct an iterator we want to serialize. | Iterator iterator = JsonList. of(1,2,3).iterator(); | | // Serialize our Iterator | String json = serializer.serialize(iterator); // Produces "[1,2,3]" | | // Try to parse it. | ReaderParser parser = JsonParser. create().swaps(IteratorSwap. class).build(); | iterator = parser.parse(json, Iterator. class); // Throws ParseException!!!