ChatGPT写一些简单不含业务逻辑的代码还不错的,代码实现逻辑结构性很清晰,虽然最终结果不对,但是可以拿来自己修改修改。文中代码和数据均为ChatGPT给出。
代码:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
public class GeoJsonConverter {
public static void main(String[] args) throws IOException {
// 读取GeoJSON文件内容
String json = new String(Files.readAllBytes(Paths.get("input.geojson")));
// 使用Jackson库解析JSON
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(json);
// 获取所有的Geometry对象
JsonNode features = root.path("features");
for (JsonNode feature : features) {
JsonNode geometry = feature.path("geometry");
// 检查Geometry类型是否为Multipolygon
String type = geometry.path("type").asText();
if (type.equals("MultiPolygon")) {
// 获取Multipolygon的所有坐标集合
ArrayNode polygons = (ArrayNode) geometry.path("coordinates");
// 遍历所有的坐标集合,并将其转换为Polygon
for (JsonNode polygon : polygons) {
ArrayNode newPolygon = mapper.createArrayNode();
newPolygon.add(polygon);
// 替换原来的Multipolygon
((com.fasterxml.jackson.databind.node.ObjectNode) geometry).put("type", "Polygon");
((com.fasterxml.jackson.databind.node.ObjectNode) geometry).set("coordinates", newPolygon);
// 输出结果
System.out.println(feature.toString());
}
}
}
}
}
数据:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "MultiPolygon",
"coordinates": [
[
[
[100.0, 0.0],
[101.0, 0.0],
[101.0, 1.0],
[100.0, 1.0],
[100.0, 0.0]
]
],
[
[
[102.0, 2.0],
[103.0, 2.0],
[103.0, 3.0],
[102.0, 3.0],
[102.0, 2.0]
]
]
]
},
"properties": {
"name": "My Multipolygon"
}
}
]
}