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

cn.allbs.hj212.ser.MapValueSegmentSerializer Maven / Gradle / Ivy

There is a newer version: 2.0.0
Show newest version
package cn.allbs.hj212.ser;

import cn.allbs.hj212.config.SegmentGenerator;
import cn.allbs.hj212.exception.SegmentFormatException;

import java.io.IOException;
import java.util.Map;

/**
 * 功能:
 *
 * @author chenQi
 */
public class MapValueSegmentSerializer
        implements SegmentSerializer {

    protected final SegmentSerializer> _valueSerializer;
    protected final Object2MapConverter _object2MapConverter;

    public MapValueSegmentSerializer(SegmentSerializer> _valueSerializer,
                                     Object2MapConverter _object2MapConverter) {
        this._valueSerializer = _valueSerializer;
        this._object2MapConverter = _object2MapConverter;
    }

    @Override
    public void serialize(SegmentGenerator generator, Object data) throws IOException, SegmentFormatException {
        if (data instanceof String) {
            String value = (String) data;
            generator.writeValue(value);
        } else {
            SegmentGenerator g = generator.writeObjectStart();
            Map map = _object2MapConverter.convert(data);
            _valueSerializer.serialize(g, map);
            generator.writeObjectEnd();
        }
    }


    /**
     * Object 转换
     */
    public interface Object2MapConverter {

        Map convert(Object src) throws SegmentFormatException;
    }

}