Serializer API

##### Table of Contents

## 1 - Serializer API

The serialization API is designed to be easily extensible by developers.
If you are writing your own serializer, you will typically subclass directly from either {@link org.apache.juneau.serializer.WriterSerializer} or {@link org.apache.juneau.serializer.OutputStreamSerializer}.

### 1.1 - The SerializerGroup class

The {@link org.apache.juneau.serializer.SerializerGroup} class represents a group of serializers registered with the media types they handle.

###### Features

The `SerializerGroup` class provides the following features:

- Finds serializers based on HTTP `Accept` header values.
- Sets common properties on all serializers in a single method call.
- Locks all serializers in a single method call.
- Clones existing groups and all serializers within the group in a single method call.

Refer to {@link org.apache.juneau.serializer.SerializerGroup} for additional information.

## 2 - Defining a new Serializer

Defining a new serializer is quite simple if you subclass directly from {@link org.apache.juneau.serializer.WriterSerializer} or {@link org.apache.juneau.serializer.OutputStreamSerializer}.
In each case, you simply need to implement a single method .

The following example shows a simple serializer that converts images to output streams using standard JRE classes.

/** Serializer for converting images to byte streams */ public class ImageSerializer extends OutputStreamSerializer { /** * Constructor. * @param propertyStore The property store containing all the settings for this object. */ public ImageSerializer(PropertyStore propertyStore) { super(propertyStore, null, "image/png", "image/jpeg"); } @Override /* Serializer */ protected void doSerialize(SerializerSession session, Object o) throws Exception { RenderedImage image = (RenderedImage)o; String mediaType = session.getProperty("mediaType"); ImageIO.write(image, mediaType.substring(mediaType.indexOf('/')+1), session.getOutputStream()); } }

Serializer that take advantage of the entire {@link org.apache.juneau.CoreObject} interface to be able to serialize arbitrary beans and POJOs is considerably more complex and outside the scope of this document.
If developing such a serializer, the best course of action would be to replicate what occurs in the {@link org.apache.juneau.json.JsonSerializer} class.