使用 Jackson 将 GeoJSON 映射到 Java
Map GeoJSON to Java with Jackson
我正在尝试使用 Jackson 库将 JSON 文件映射到 Java 对象。此 json 文件是一个多级文件,可在此处找到:
https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.geojson
这是美国最近30天发生的地震列表。
下面是这个子文件的结构:https://earthquake.usgs.gov/earthquakes/feed/v1.0/geojson.php
现在,我写了一个 Java 程序,它正在从这个文件中读取字段,具体来说,我试图访问功能 -> 属性 -> 位置下的字段(例如来自原始文件 "place":"17km NW of Pinnacles, CA")).当我到达属性字段时,我可以将其作为 LinkedHashMap 读取,但是下一级,因此此 LinkedHashMap 的键和值被读取为字符串:
例如,这是以下值之一:{type=Point, coordinates=[-121.2743333, 36.6375, 8.61]}
我想将这些值作为另一个对象(不是字符串,也许是 MAP?)来读取,这样我就可以从中提取更多数据。
这是我的 class:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.ObjectMapper;
@JsonIgnoreProperties(ignoreUnknown = true)
public class ReadJSONFile {
private StringBuffer stringBuffer = new StringBuffer();
public void convert_json_to_java() throws Exception {
String url = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.geojson";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in .readLine()) != null) {
stringBuffer.append(inputLine);
stringBuffer.append("\n");
} in.close();
}
@SuppressWarnings("unchecked")
public void map_to_object() throws Exception {
ObjectMapper om = new ObjectMapper();
//ignore fields that are not formatted properly
om.configure(org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Map<Object, Object> resultMap = om.readValue(stringBuffer.toString(), Map.class);
ArrayList<Object> featuresArrayList = (ArrayList<Object>) resultMap.get("features");
for(Object o : featuresArrayList) {
LinkedHashMap<Object, Object> propertiesMap = (LinkedHashMap<Object, Object>) o;
for(Map.Entry<Object, Object> entry : propertiesMap.entrySet()) {
//HERE IS THE PROBLEM, THE VALUES OF THIS MAP (SECOND OBJECT) IS BEING READ AS A STRING
//WHILE SOME VALUES ARE NOT A STRING:
//e.g. {type=Point, coordinates=[-121.2743333, 36.6375, 8.61]}
//AND I WANT TO READ IT AS A MAP OR ANY OTHER OBJECT THAT WOULD ALLOW ME TO ACCESS THE DATA
String propertiesMapValues = entry.getValue().toString();
}
}
}
}
Main.java
public class Main {
public static void main(String[] args) throws Exception {
ReadJSONFile rjf = new ReadJSONFile();
rjf.convert_json_to_java();
rjf.map_to_object();
}
}
Maven 依赖项:https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-asl
当我尝试将最后一个对象转换为 String 以外的任何对象时,程序出现异常(无法将 String 转换为另一个对象)。我做错什么了吗?有人能告诉我如何在不修改字符串的情况下访问这些字段(例如,将它们拆分成数组等)吗?
实际上您的代码可以工作,但可以稍微简化一下。方法convert_json_to_java
是不必要的,你可以将URL直接传递给ObjectMapper。
地图中的值未作为字符串读取,但您通过调用为所有对象定义的 toString()
将它们转换为字符串。实际类型可以是Map、List、String、Integer等,具体取决于JSON内容。使用通用映射确实有点烦人,所以我建议您将值转换为结构化对象。 GeoJSON 是一个开放标准,因此有一些开源库可以方便地使用它,例如geojson-jackson。
您需要添加 Maven 依赖项:
<dependency>
<groupId>de.grundid.opendatalab</groupId>
<artifactId>geojson-jackson</artifactId>
<version>1.8.1</version>
</dependency>
那么程序可能类似于:
import org.geojson.*
// ...
public class ReadJSONFile {
ObjectMapper om = new ObjectMapper();
public void mapToObject(String url) throws Exception {
Map<String, Object> resultMap = om.readValue(new URL(url), new TypeReference<Map<String, Object>>() {});
List<Feature> features = om.convertValue(resultMap.get("features"), new TypeReference<List<Feature>>() {});
for(Feature f : features) {
// Write the feature to the console to see how it looks like
System.out.println(om.writeValueAsString(f));
// Extract properties
Map<String,Object> properties = f.getProperties();
// ....
// Extract geometry
GeoJsonObject geometry = f.getGeometry();
if(geometry instanceof Point) {
Point p = (Point) geometry;
// do something with the point
} else if(geometry instanceof LineString) {
LineString mls = (LineString) geometry;
// ...
} else if(geometry instanceof MultiLineString) {
MultiLineString mls = (MultiLineString) geometry;
// ...
} else if(geometry instanceof MultiPoint) {
MultiPoint mp = (MultiPoint) geometry;
// ...
} else if(geometry instanceof Polygon) {
Polygon pl = (Polygon) geometry;
// ...
} else if(geometry != null) {
throw new RuntimeException("Unhandled geometry type: " + geometry.getClass().getName());
}
}
}
public static void main(String[] args) throws Exception {
ReadJSONFile rjf = new ReadJSONFile();
rjf.mapToObject("https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.geojson");
}
}
我正在尝试使用 Jackson 库将 JSON 文件映射到 Java 对象。此 json 文件是一个多级文件,可在此处找到:
https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.geojson
这是美国最近30天发生的地震列表。
下面是这个子文件的结构:https://earthquake.usgs.gov/earthquakes/feed/v1.0/geojson.php
现在,我写了一个 Java 程序,它正在从这个文件中读取字段,具体来说,我试图访问功能 -> 属性 -> 位置下的字段(例如来自原始文件 "place":"17km NW of Pinnacles, CA")).当我到达属性字段时,我可以将其作为 LinkedHashMap 读取,但是下一级,因此此 LinkedHashMap 的键和值被读取为字符串:
例如,这是以下值之一:{type=Point, coordinates=[-121.2743333, 36.6375, 8.61]}
我想将这些值作为另一个对象(不是字符串,也许是 MAP?)来读取,这样我就可以从中提取更多数据。
这是我的 class:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.ObjectMapper;
@JsonIgnoreProperties(ignoreUnknown = true)
public class ReadJSONFile {
private StringBuffer stringBuffer = new StringBuffer();
public void convert_json_to_java() throws Exception {
String url = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.geojson";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in .readLine()) != null) {
stringBuffer.append(inputLine);
stringBuffer.append("\n");
} in.close();
}
@SuppressWarnings("unchecked")
public void map_to_object() throws Exception {
ObjectMapper om = new ObjectMapper();
//ignore fields that are not formatted properly
om.configure(org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Map<Object, Object> resultMap = om.readValue(stringBuffer.toString(), Map.class);
ArrayList<Object> featuresArrayList = (ArrayList<Object>) resultMap.get("features");
for(Object o : featuresArrayList) {
LinkedHashMap<Object, Object> propertiesMap = (LinkedHashMap<Object, Object>) o;
for(Map.Entry<Object, Object> entry : propertiesMap.entrySet()) {
//HERE IS THE PROBLEM, THE VALUES OF THIS MAP (SECOND OBJECT) IS BEING READ AS A STRING
//WHILE SOME VALUES ARE NOT A STRING:
//e.g. {type=Point, coordinates=[-121.2743333, 36.6375, 8.61]}
//AND I WANT TO READ IT AS A MAP OR ANY OTHER OBJECT THAT WOULD ALLOW ME TO ACCESS THE DATA
String propertiesMapValues = entry.getValue().toString();
}
}
}
}
Main.java
public class Main {
public static void main(String[] args) throws Exception {
ReadJSONFile rjf = new ReadJSONFile();
rjf.convert_json_to_java();
rjf.map_to_object();
}
}
Maven 依赖项:https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-asl
当我尝试将最后一个对象转换为 String 以外的任何对象时,程序出现异常(无法将 String 转换为另一个对象)。我做错什么了吗?有人能告诉我如何在不修改字符串的情况下访问这些字段(例如,将它们拆分成数组等)吗?
实际上您的代码可以工作,但可以稍微简化一下。方法convert_json_to_java
是不必要的,你可以将URL直接传递给ObjectMapper。
地图中的值未作为字符串读取,但您通过调用为所有对象定义的 toString()
将它们转换为字符串。实际类型可以是Map、List、String、Integer等,具体取决于JSON内容。使用通用映射确实有点烦人,所以我建议您将值转换为结构化对象。 GeoJSON 是一个开放标准,因此有一些开源库可以方便地使用它,例如geojson-jackson。
您需要添加 Maven 依赖项:
<dependency>
<groupId>de.grundid.opendatalab</groupId>
<artifactId>geojson-jackson</artifactId>
<version>1.8.1</version>
</dependency>
那么程序可能类似于:
import org.geojson.*
// ...
public class ReadJSONFile {
ObjectMapper om = new ObjectMapper();
public void mapToObject(String url) throws Exception {
Map<String, Object> resultMap = om.readValue(new URL(url), new TypeReference<Map<String, Object>>() {});
List<Feature> features = om.convertValue(resultMap.get("features"), new TypeReference<List<Feature>>() {});
for(Feature f : features) {
// Write the feature to the console to see how it looks like
System.out.println(om.writeValueAsString(f));
// Extract properties
Map<String,Object> properties = f.getProperties();
// ....
// Extract geometry
GeoJsonObject geometry = f.getGeometry();
if(geometry instanceof Point) {
Point p = (Point) geometry;
// do something with the point
} else if(geometry instanceof LineString) {
LineString mls = (LineString) geometry;
// ...
} else if(geometry instanceof MultiLineString) {
MultiLineString mls = (MultiLineString) geometry;
// ...
} else if(geometry instanceof MultiPoint) {
MultiPoint mp = (MultiPoint) geometry;
// ...
} else if(geometry instanceof Polygon) {
Polygon pl = (Polygon) geometry;
// ...
} else if(geometry != null) {
throw new RuntimeException("Unhandled geometry type: " + geometry.getClass().getName());
}
}
}
public static void main(String[] args) throws Exception {
ReadJSONFile rjf = new ReadJSONFile();
rjf.mapToObject("https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.geojson");
}
}