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

com.jamierf.dbtable.jackson.codec.ObjectMapperCodec Maven / Gradle / Ivy

package com.jamierf.dbtable.jackson.codec;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Function;
import com.google.common.base.Throwables;

import javax.annotation.Nullable;
import java.io.IOException;

public class ObjectMapperCodec {

    private final ObjectMapper mapper;

    public ObjectMapperCodec(ObjectMapper mapper) {
        this.mapper = mapper;
    }

    public  Function newEncoder() {
        return new Function() {
            @Nullable
            @Override
            public byte[] apply(@Nullable T input) {
                try {
                    return mapper.writeValueAsBytes(input);
                } catch (JsonProcessingException e) {
                    throw Throwables.propagate(e);
                }
            }
        };
    }

    public  Function newDecoder(final Class type) {
        return new Function() {
            @Nullable
            @Override
            public T apply(@Nullable byte[] input) {
                try {
                    return mapper.readValue(input, type);
                } catch (IOException e) {
                    throw Throwables.propagate(e);
                }
            }
        };
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy