3 Star 13 Fork 5

10km/sql2java

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
JsonColumnCodec.java 2.01 KB
一键复制 编辑 原始数据 按行查看 历史
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> T doDeserialize(Object columnValue, Class<T> targetType) throws ResultSetCodecException {
return doDeserialize(columnValue,(Type)targetType);
}
protected <T> 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> T doSerialize(Object obj, Class<T> 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());
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/l0km/sql2java.git
git@gitee.com:l0km/sql2java.git
l0km
sql2java
sql2java
master

搜索帮助

344bd9b3 5694891 D2dac590 5694891