package com.ag.redis;

import com.ag.util.StrUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.util.Assert;

import java.nio.charset.Charset;

/**
 * Created by yangxh on 2021/3/20.
 */
public class StringRedisSerializer implements RedisSerializer<Object> {
    private final Charset charset;


    public StringRedisSerializer() {
        this(Charset.forName("UTF8"));
    }

    public StringRedisSerializer(Charset charset) {
        Assert.notNull(charset, "Charset must not be null!");
        this.charset = charset;
    }

    @Override
    public String deserialize(byte[] bytes) {
        return (bytes == null ? null : new String(bytes, charset));
    }

    /*@Override
    public byte[] serialize(Object object) {
        String string = JSON.toJSONString(object);
        if (StrUtil.isEmpty(string)) {
            return null;
        }
        return string.getBytes(charset);
    }*/

    @Override
    public byte[] serialize(Object object) {
        String string = JSON.toJSONString(object);
        if (StrUtil.isEmpty(string)) {
            return null;
        }
        if (string.startsWith("\"")){
            string = string.substring(0, string.length()-1).substring(1);
        }
        return string.getBytes(charset);
    }

    /*public static void main(String[] args) {
        String a ="\"a\"b\"c\"d\"";
        System.out.println(a);
        System.out.println(a.substring(0,a.length()-1).substring(1));
    }*/
}
