gu.sql2java.geometry.fastjson.GeometryCodec 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.geometry.fastjson;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;
import java.io.IOException;
import java.lang.reflect.Type;
/**
* JTS几何对象FASTJSON序列化反序列化实现
* 参见 JTS Topology Suite
* @author guyadong
*
* @param
* @since 3.18.0
*/
public class GeometryCodec implements ObjectSerializer, ObjectDeserializer {
/**
* 将geometry类型序列化为WKT JSON字符串
*/
@SuppressWarnings("unchecked")
@Override
public void write(JSONSerializer jsonSerializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
T geom = (T) object;
jsonSerializer.write(geom.toString());
}
/**
* 将WKT字符串反序列为{@link Geometry}
*/
@SuppressWarnings("unchecked")
@Override
public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
Object value = parser.parse();
if (value == null) {
return null;
} else {
String wkt = (String) value;
WKTReader reader = new WKTReader();
try {
return (T) reader.read(wkt);
} catch (ParseException e) {
throw new JSONException(e.getMessage(),e);
}
}
}
@Override
public int getFastMatchToken() {
return 0;
}
}