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

se.l4.commons.serialization.collections.MapAsObjectSerializer 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.HashMap;
import java.util.Map;
import java.util.Map.Entry;

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;

public class MapAsObjectSerializer
	implements Serializer>
{
	private final Serializer serializer;
	private final SerializerFormatDefinition formatDefinition;

	public MapAsObjectSerializer(Serializer serializer)
	{
		this.serializer = serializer;
		
		formatDefinition = SerializerFormatDefinition.builder()
			.field("*").using(serializer)
			.build();
	}
	
	@Override
	public Map read(StreamingInput in)
		throws IOException
	{
		in.next(Token.OBJECT_START);
		
		Map result = new HashMap();
		while(in.peek() != Token.OBJECT_END)
		{
			in.next(Token.KEY);
			String key = in.getString();
			if(key.startsWith("_aurochs_:"))
			{
				in.skipValue();
				continue;
			}
			
			V value = in.peek() == Token.NULL ? null : serializer.read(in);
			
			result.put(key, value);
		}
		
		in.next(Token.OBJECT_END);
		
		return result;
	}
	
	@Override
	public void write(Map object, String name, StreamingOutput stream)
		throws IOException
	{
		stream.writeObjectStart(name);
		
		for(Entry e : object.entrySet())
		{
			V value = e.getValue();
			if(value == null)
			{
				stream.writeNull(name);
			}
			else
			{
				serializer.write(value, e.getKey(), stream);
			}
		}
		
		stream.writeObjectEnd(name);
	}
	
	@Override
	public SerializerFormatDefinition getFormatDefinition()
	{
		return formatDefinition;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy