se.l4.commons.serialization.collections.ListSerializer Maven / Gradle / Ivy
package se.l4.commons.serialization.collections;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.RandomAccess;
import se.l4.commons.serialization.Serializer;
import se.l4.commons.serialization.SerializerFormatDefinition;
import se.l4.commons.serialization.format.StreamingInput;
import se.l4.commons.serialization.format.StreamingOutput;
import se.l4.commons.serialization.format.Token;
/**
* Serializer for {@link List}.
*
* @author Andreas Holstenson
*
* @param
*/
public class ListSerializer
implements Serializer>
{
private final Serializer itemSerializer;
private final SerializerFormatDefinition formatDefinition;
public ListSerializer(Serializer itemSerializer)
{
this.itemSerializer = itemSerializer;
formatDefinition = SerializerFormatDefinition.builder()
.list(itemSerializer)
.build();
}
@Override
public List read(StreamingInput in)
throws IOException
{
in.next(Token.LIST_START);
List list = new ArrayList();
while(in.peek() != Token.LIST_END)
{
T value;
if(in.peek() == Token.NULL)
{
in.next();
value = null;
}
else
{
value = itemSerializer.read(in);
}
list.add(value);
}
in.next(Token.LIST_END);
return list;
}
@Override
public void write(List object, String name, StreamingOutput stream)
throws IOException
{
stream.writeListStart(name);
if(object instanceof RandomAccess)
{
for(int i=0, n=object.size(); i