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

se.l4.commons.serialization.collections.SetSerializer 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.util.HashSet;
import java.util.List;
import java.util.Set;

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 SetSerializer
	implements Serializer>
{
	private final Serializer itemSerializer;
	private final SerializerFormatDefinition formatDefinition;

	public SetSerializer(Serializer itemSerializer)
	{
		this.itemSerializer = itemSerializer;
		
		formatDefinition = SerializerFormatDefinition.builder()
			.list(itemSerializer)
			.build();
	}

	@Override
	public Set read(StreamingInput in)
		throws IOException
	{
		in.next(Token.LIST_START);
		
		Set list = new HashSet();
		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(Set object, String name, StreamingOutput stream)
		throws IOException
	{
		stream.writeListStart(name);
		
		for(T value : object)
		{
			if(value == null)
			{
				stream.writeNull("item");
			}
			else
			{
				itemSerializer.write(value, "item", stream);
			}
		}
		
		stream.writeListEnd(name);
	}
	
	@Override
	public SerializerFormatDefinition getFormatDefinition()
	{
		return formatDefinition;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy