gpt4 book ai didi

java - 使用 Jackson 将 GeoJSON 映射到 Java

转载 作者:行者123 更新时间:2023-11-30 01:42:40 26 4
gpt4 key购买 nike

我正在尝试使用 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加利福尼亚州尖峰石阵"))。当我到达属性字段时,我可以将其读取为 LinkedHashMap,但是是下一个级别,因此此 LinkedHashMap 的键和值将被读取为字符串:

例如,这是值之一:{type=Point, Cocoles=[-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");
}
}

关于java - 使用 Jackson 将 GeoJSON 映射到 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59416836/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com