gu.sql2java.json.JsonColumnCodec Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of sql2java-base Show documentation
Show all versions of sql2java-base Show documentation
sql2java common class package
package gu.sql2java.json;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import gu.sql2java.BaseColumnCodec;
import gu.sql2java.exception.ResultSetCodecException;
import gu.sql2java.exception.UnsupportTypeException;
import static com.alibaba.fastjson.serializer.SerializerFeature.WriteDateUseDateFormat;
import static com.alibaba.fastjson.serializer.SerializerFeature.WriteNonStringKeyAsString;
import java.lang.reflect.Type;
/**
* 基于fastjson的JSON/String字段编解码实现
* @author guyadong
* @since 3.21.0
*/
public class JsonColumnCodec extends BaseColumnCodec {
@Override
protected T doDeserialize(Object columnValue, Class targetType) throws ResultSetCodecException {
return doDeserialize(columnValue,(Type)targetType);
}
protected T doDeserialize(Object columnValue, Type targetType) throws ResultSetCodecException {
if(columnValue instanceof String) {
try {
return JSON.parseObject((String)columnValue,targetType);
} catch (JSONException e) {
throw new ResultSetCodecException(e);
}
}
if(columnValue instanceof byte[]) {
try {
return JSON.parseObject((byte[])columnValue,targetType);
} catch (JSONException e) {
throw new ResultSetCodecException(e);
}
}
throw new UnsupportTypeException("UNSUPPORTED type of columnValue " + columnValue.getClass().getName());
}
@SuppressWarnings("unchecked")
@Override
protected T doSerialize(Object obj, Class targetType) throws ResultSetCodecException {
if(String.class.equals(targetType)) {
try {
return (T) JSON.toJSONString(obj, WriteDateUseDateFormat,WriteNonStringKeyAsString);
} catch (JSONException e) {
throw new ResultSetCodecException(e);
}
}
if (byte[].class.equals(targetType)) {
try {
return (T) JSON.toJSONBytes(obj, WriteDateUseDateFormat,WriteNonStringKeyAsString);
} catch (JSONException e) {
throw new ResultSetCodecException(e);
}
}
throw new UnsupportTypeException("UNSUPPORTED type of targetType " + targetType.getName());
}
}