com.alibaba.fastjson2.support.spring6.data.redis.FastJsonRedisSerializer Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of fastjson2-extension-spring6 Show documentation
Show all versions of fastjson2-extension-spring6 Show documentation
Fastjson is a JSON processor (JSON parser + JSON generator) written in Java
The newest version!
package com.alibaba.fastjson2.support.spring6.data.redis;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONB;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
/**
* Fastjson for Spring Data Redis Serializer.
*
* @author lihengming
* @author Victor.Zxy
* @see RedisSerializer
* @since 2.0.23
*/
public class FastJsonRedisSerializer
implements RedisSerializer {
private FastJsonConfig config = new FastJsonConfig();
private final Class type;
public FastJsonRedisSerializer(Class type) {
this.type = type;
}
public FastJsonConfig getFastJsonConfig() {
return config;
}
public void setFastJsonConfig(FastJsonConfig fastJsonConfig) {
this.config = fastJsonConfig;
}
@Override
public byte[] serialize(T t) throws SerializationException {
if (t == null) {
return new byte[0];
}
try {
if (config.isJSONB()) {
return JSONB.toBytes(t, config.getSymbolTable(), config.getWriterFilters(), config.getWriterFeatures());
} else {
return JSON.toJSONBytes(t, config.getDateFormat(), config.getWriterFilters(), config.getWriterFeatures());
}
} catch (Exception ex) {
throw new SerializationException("Could not serialize: " + ex.getMessage(), ex);
}
}
@Override
public T deserialize(byte[] bytes) throws SerializationException {
if (bytes == null || bytes.length == 0) {
return null;
}
try {
if (config.isJSONB()) {
return JSONB.parseObject(bytes, type, config.getSymbolTable(), config.getReaderFilters(), config.getReaderFeatures());
} else {
return JSON.parseObject(bytes, type, config.getDateFormat(), config.getReaderFilters(), config.getReaderFeatures());
}
} catch (Exception ex) {
throw new SerializationException("Could not deserialize: " + ex.getMessage(), ex);
}
}
}