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

com.netflix.astyanax.serializers.JacksonSerializer Maven / Gradle / Ivy

There is a newer version: 3.10.2
Show newest version
package com.netflix.astyanax.serializers;

import java.io.ByteArrayInputStream;
import java.nio.ByteBuffer;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize;

public class JacksonSerializer extends AbstractSerializer {
    private static final ObjectMapper mapper = new ObjectMapper();

    static {
        mapper.getSerializationConfig().withSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);
        mapper.enableDefaultTyping();
    }
    
    private final Class clazz;

    public JacksonSerializer(Class clazz) {
        this.clazz = clazz;
    }

    @Override
    public ByteBuffer toByteBuffer(T entity) {
        try {
            byte[] bytes = mapper.writeValueAsBytes(entity);
            return ByteBuffer.wrap(bytes);
        } catch (Exception e) {
            throw new RuntimeException("Error serializing entity ", e);
        }
    }

    @Override
    public T fromByteBuffer(ByteBuffer byteBuffer) {
        try {
            return mapper.readValue(new ByteArrayInputStream(byteBuffer.array()), clazz);
        } catch (Exception e) {
            throw new RuntimeException("Error serializing entity ", e);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy