se.l4.commons.serialization.collections.SetSerializer Maven / Gradle / Ivy
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;
}
}