All Downloads are FREE. Search and download functionalities are using the official Maven repository.

se.l4.commons.serialization.collections.ArraySerializer Maven / Gradle / Ivy

There is a newer version: 0.4.2
Show newest version
package se.l4.commons.serialization.collections;

import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

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 arrays.
 * 
 * @author Andreas Holstenson
 *
 */
public class ArraySerializer
	implements Serializer
{
	private final Class componentType;
	@SuppressWarnings("rawtypes")
	private final Serializer itemSerializer;
	private final SerializerFormatDefinition formatDefinition;

	public ArraySerializer(Class componentType, Serializer itemSerializer)
	{
		this.componentType = componentType;
		this.itemSerializer = itemSerializer;
		
		formatDefinition = SerializerFormatDefinition.builder()
			.list(itemSerializer)
			.build();
	}
	
	@Override
	public Object read(StreamingInput in)
		throws IOException
	{
		in.next(Token.LIST_START);
		
		List list = new ArrayList();
		while(in.peek() != Token.LIST_END)
		{
			Object value = in.peek() == Token.NULL ? null : itemSerializer.read(in);
			list.add(value);
		}
		
		in.next(Token.LIST_END);
		
		Object array = Array.newInstance(componentType, list.size());
		for(int i=0, n=list.size(); i