仿GeometryJson 转换GeoJSON Jackson序列化类 v1
工具类
import org.locationtech.jts.geom.*;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class GeoJsonUtils {
private GeoJsonUtils() {
}
private static GeoJsonUtils INSTANCE = new GeoJsonUtils();
private double scale = 6;
public static Map<String, Object> getFeature(Geometry geometry) {
Map<String, Object> map = INSTANCE.create(geometry);
return map;
}
public Object getCoordinates(Geometry geometry) {
final Map<String, Object> feature = getFeature(geometry);
if (feature.containsKey("geometries")) {
return feature.get("geometries");
}
return feature.get("coordinates");
}
private Map<String, Object> create(Geometry geometry) {
if (geometry instanceof Point) {
return this.createPoint((Point) geometry);
} else if (geometry instanceof LineString) {
return this.createLine((LineString) geometry);
} else if (geometry instanceof Polygon) {
return this.createPolygon((Polygon) geometry);
} else if (geometry instanceof MultiPoint) {
return this.createMultiPoint((MultiPoint) geometry);
} else if (geometry instanceof MultiLineString) {
return this.createMultiLine((MultiLineString) geometry);
} else if (geometry instanceof MultiPolygon) {
return this.createMultiPolygon((MultiPolygon) geometry);
} else if (geometry instanceof GeometryCollection) {
return this.createGeometryCollection((GeometryCollection) geometry);
} else {
throw new IllegalArgumentException("Unable to encode object " + geometry);
}
}
private Map<String, Object> createPoint(Point point) {
LinkedHashMap<String, Object> obj = new LinkedHashMap<>();
obj.put("type", "Point");
obj.put("coordinates", new CoordinateSequenceEncoder(point.getCoordinateSequence(), this.scale).toArray());
return obj;
}
private Map<String, Object> createLine(LineString line) {
LinkedHashMap<String, Object> obj = new LinkedHashMap<>();
obj.put("type", "LineString");
obj.put("coordinates", new CoordinateSequenceEncoder(line.getCoordinateSequence(), this.scale).toArray());
return obj;
}
private Map<String, Object> createPolygon(Polygon poly) {
LinkedHashMap<String, Object> obj = new LinkedHashMap<>();
obj.put("type", "Polygon");
obj.put("coordinates", this.toList(poly));
return obj;
}
private Map<String, Object> createMultiPoint(MultiPoint mpoint) {
LinkedHashMap<String, Object> obj = new LinkedHashMap<>();
obj.put("type", "MultiPoint");
obj.put("coordinates", this.toList((GeometryCollection) mpoint));
return obj;
}
private Map<String, Object> createMultiLine(MultiLineString mline) {
LinkedHashMap<String, Object> obj = new LinkedHashMap<>();
obj.put("type", "MultiLineString");
obj.put("coordinates", this.toList((GeometryCollection) mline));
return obj;
}
private Map<String, Object> createMultiPolygon(MultiPolygon mpoly) {
LinkedHashMap<String, Object> obj = new LinkedHashMap<>();
obj.put("type", "MultiPolygon");
obj.put("coordinates", this.toList((GeometryCollection) mpoly));
return obj;
}
private Map<String, Object> createGeometryCollection(GeometryCollection gcol) {
LinkedHashMap<String, Object> obj = new LinkedHashMap<>();
ArrayList<Map<String, Object>> geoms = new ArrayList<>(gcol.getNumGeometries());
for (int i = 0; i < gcol.getNumGeometries(); ++i) {
geoms.add(this.create(gcol.getGeometryN(i)));
}
obj.put("type", "GeometryCollection");
obj.put("geometries", geoms);
return obj;
}
private List<Object> toList(Polygon poly) {
ArrayList<Object> list = new ArrayList<>();
list.add(new CoordinateSequenceEncoder(poly.getExteriorRing().getCoordinateSequence(), this.scale).toArray());
for (int i = 0; i < poly.getNumInteriorRing(); ++i) {
list.add(new CoordinateSequenceEncoder(poly.getInteriorRingN(i).getCoordinateSequence(), this.scale).toArray());
}
return list;
}
private List toList(GeometryCollection mgeom) {
ArrayList<Object> list = new ArrayList<>(mgeom.getNumGeometries());
for (int i = 0; i < mgeom.getNumGeometries(); ++i) {
Geometry g = mgeom.getGeometryN(i);
if (g instanceof Polygon) {
list.add(this.toList((Polygon) g));
} else if (g instanceof LineString) {
list.add(new CoordinateSequenceEncoder(((LineString) g).getCoordinateSequence(), this.scale).toArray());
} else if (g instanceof Point) {
list.add(new CoordinateSequenceEncoder(((Point) g).getCoordinateSequence(), this.scale).toArray());
}
}
return list;
}
public static class CoordinateSequenceEncoder {
private static final double DECIMAL_MIN = Math.pow(10.0D, -3.0D);
private static final double DECIMAL_MAX = Math.pow(10.0D, 7.0D);
CoordinateSequence seq;
double scale;
CoordinateSequenceEncoder(CoordinateSequence seq, double scale) {
this.seq = seq;
this.scale = scale;
}
@Override
public String toString() {
int size = this.seq.size();
StringBuilder sb = new StringBuilder();
if (size > 1) {
sb.append("[");
}
for (int i = 0; i < this.seq.size(); ++i) {
Coordinate coordinate = this.seq.getCoordinate(i);
sb.append("[");
this.formatDecimal(coordinate.x, sb);
sb.append(",");
this.formatDecimal(coordinate.y, sb);
if (!Double.isNaN(coordinate.getZ())) {
sb.append(",");
this.formatDecimal(coordinate.getZ(), sb);
}
sb.append("],");
}
sb.setLength(sb.length() - 1);
if (size > 1) {
sb.append("]");
}
return sb.toString();
}
public Object toArray() {
int size = this.seq.size();
StringBuilder sb = new StringBuilder();
if (size > 1) {
sb.append("[");
}
for (int i = 0; i < this.seq.size(); ++i) {
Coordinate coordinate = this.seq.getCoordinate(i);
sb.append("[");
this.formatDecimal(coordinate.x, sb);
sb.append(",");
this.formatDecimal(coordinate.y, sb);
if (!Double.isNaN(coordinate.getZ())) {
sb.append(",");
this.formatDecimal(coordinate.getZ(), sb);
}
sb.append("],");
}
sb.setLength(sb.length() - 1);
if (size > 1) {
sb.append("]");
}
if (1 == size) {
return JacksonUtils.parseDoubleArrStr(sb.toString());
}
return JacksonUtils.parseDouble2ArrStr(sb.toString());
}
public void writeJSONString(Writer out) throws IOException {
int size = this.seq.size();
if (size > 1) {
out.write("[");
}
for (int i = 0; i < this.seq.size(); ++i) {
Coordinate coordinate = this.seq.getCoordinate(i);
out.write("[");
out.write(String.valueOf(coordinate.x));
out.write(",");
out.write(String.valueOf(coordinate.y));
if (!Double.isNaN(coordinate.getZ())) {
out.write(",");
out.write(String.valueOf(coordinate.getZ()));
}
out.write("]");
if (i < this.seq.size() - 1) {
out.write(",");
}
}
if (size > 1) {
out.write("]");
}
}
private void formatDecimal(double x, StringBuilder sb) {
if (Math.abs(x) >= DECIMAL_MIN && x < DECIMAL_MAX) {
x = Math.floor(x * this.scale + 0.5D) / this.scale;
long lx = (long) x;
if ((double) lx == x) {
sb.append(lx);
} else {
sb.append(x);
}
} else {
sb.append(x);
}
}
}
}
序列化类
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.locationtech.jts.geom.Geometry;
import java.io.IOException;
public class ToJsonGeometrySerializer extends JsonSerializer<Geometry> {
@Override
public Class<Geometry> handledType() {
return Geometry.class;
}
@Override
public void serialize(Geometry geometry, JsonGenerator gen, SerializerProvider provider) throws IOException {
if (geometry == null) {
gen.writeNull();
return;
}
gen.writeObject(GeoJsonUtils.getFeature(geometry));
}
}
注册到jackson中
public final class JacksonUtils {
private static ObjectMapper OBJECT_MAPPER;
private JacksonUtils() {
}
static {
init();
}
private static void init() {
OBJECT_MAPPER = new ObjectMapper();
OBJECT_MAPPER.addSerializer(new ToJsonGeometrySerializer());
}
public static Double[] parseDoubleArrStr(String json) {
try {
return OBJECT_MAPPER.readValue(json, Double[].class);
} catch (JsonProcessingException e) {
log.error("解析json数据失败", e);
throw BizException.newInstance(String.format("解析json数据失败 %s", e.getMessage()));
}
}
public static Double[][] parseDouble2ArrStr(String json) {
try {
return OBJECT_MAPPER.readValue(json, Double[][].class);
} catch (JsonProcessingException e) {
log.error("解析json数据失败", e);
throw BizException.newInstance(String.format("解析json数据失败 %s", e.getMessage()));
}
}
}