All Downloads are FREE. Search and download functionalities are using the official Maven repository.

gu.sql2java.json.JsonColumnCodec Maven / Gradle / Ivy

There is a newer version: 5.2.0
Show newest version
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());
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy