com.kasinf.framework.rest.eneity.converter.JsonConverter Maven / Gradle / Ivy
package com.kasinf.framework.rest.eneity.converter;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
/**
* JPA 2.1 属性转换器,将fastjson的JSONArray或JSONObject转换为字符串
* @author lkhsh
*/
@Converter
public class JsonConverter implements AttributeConverter {
@Override
public String convertToDatabaseColumn(JSON attribute) {
return attribute == null ? "" : JSON.toJSONString(attribute);
}
@Override
public JSON convertToEntityAttribute(String dbData) {
if (StrUtil.isEmpty(dbData)){
return null;
}
JSON rtn;
try {
rtn = JSON.parseObject(dbData);
} catch (JSONException e) {
rtn = JSON.parseArray(dbData);
}
return rtn;
}
}