package com.community.commom.redis;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.Serializable;

/**
 * redis json 序列化工具
 * @author gengxiang
 * @create 2017-09-06 18:04
 *
 **/
public class RedisJsonSerializer implements RedisSerializer {
    private static final ObjectMapper mapper = new ObjectMapper();

    static {
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    @Override
    public <T> T deserialize(byte[] source, Class<T> tClass) throws SerializationFailedException {
        try {
            if (source == null)
                return null;
            if (tClass == String.class)
                return tClass.cast(new String(source));
            return mapper.readValue(source, tClass);
        } catch (Exception e) {
            throw new SerializationFailedException("Deserialize failed:" + e, e);
        }
    }

    @Override
    public byte[] serialize(Object object) throws SerializationFailedException {
        if (!(object instanceof Serializable)) {
            throw new IllegalArgumentException("Serializer requires a Serializable payload " + "but received an object of type [" + object.getClass().getName() + "]");
        }
        try {
            if (object instanceof String)
                return object.toString().getBytes();
            return mapper.writeValueAsString(object).getBytes("UTF-8");
        } catch (Exception e) {
            throw new SerializationFailedException("Serialize failed:" + object.getClass(), e);
        }
    }
}
