-
Notifications
You must be signed in to change notification settings - Fork 54
/
GeoJSONFactory.java
72 lines (61 loc) · 2.74 KB
/
GeoJSONFactory.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package org.wololo.geojson;
import java.io.IOException;
import java.util.Map;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class GeoJSONFactory {
private static final ObjectMapper mapper = new ObjectMapper();
public static GeoJSON create(String json) {
try {
JsonNode node = mapper.readTree(json);
String type = node.get("type").asText();
if (type.equals("FeatureCollection")) {
return readFeatureCollection(node);
} else if (type.equals("Feature")) {
return readFeature(node);
} else {
return readGeometry(node, type);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static FeatureCollection readFeatureCollection(JsonNode node)
throws JsonParseException, JsonMappingException, IOException, ClassNotFoundException {
Iterator<JsonNode> it = node.get("features").iterator();
List<Feature> features = new ArrayList<Feature>();
while (it.hasNext()) {
JsonNode jFeature = it.next();
features.add(readFeature(jFeature));
}
return new FeatureCollection(features.toArray(new Feature[features.size()]));
}
private static Feature readFeature(JsonNode node)
throws JsonParseException, JsonMappingException, IOException, ClassNotFoundException {
JsonNode geometryNode = node.get("geometry");
JavaType javaType = mapper.getTypeFactory().constructMapType(Map.class, String.class, Object.class);
Object id = node.get("id");
Map<String, Object> properties = mapper.readValue(node.get("properties").traverse(), javaType);
Geometry geometry = readGeometry(geometryNode);
return new Feature(id, geometry, properties);
}
private static Geometry readGeometry(JsonNode node)
throws JsonParseException, JsonMappingException, IOException, ClassNotFoundException {
if (!node.isNull()) {
final String type = node.get("type").asText();
return readGeometry(node, type);
} else {
return null;
}
}
private static Geometry readGeometry(JsonNode node, String type)
throws JsonParseException, JsonMappingException, IOException, ClassNotFoundException {
return (Geometry) mapper.readValue(node.traverse(), Class.forName("org.wololo.geojson." + type));
}
}