如何将 JSON 对象列表转换为 JsonArray 然后对其进行迭代?

How to convert list of JSON objects to JsonArray and then iterate on it?

我正在尝试将带有 JSON 个对象的字符串(每个 JSON 对象用逗号分隔,但第一个 JSON 对象是该集合的描述)转换为 JsonArray 然后我尝试迭代每个 JsonElement 的某些子元素,但每次尝试都以错误告终。

字符串示例:

{"type":"FeatureCollection","metadata":{"generated":1554314439000,"url":"https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&eventtype=earthquake","title":"USGS Earthquakes","status":200,"api":"1.7.0","count":8970},"features":[{"type":"Feature","properties":{"mag":2.2,"place":"84km SSE of Old Iliamna, Alaska","time":1554313967537,"updated":1554314345998,"tz":-540,"url":"https://earthquake.usgs.gov/earthquakes/eventpage/ak0194a3ew0w","detail":"https://earthquake.usgs.gov/fdsnws/event/1/query?eventid=ak0194a3ew0w&format=geojson","felt":null,"cdi":null,"mmi":null,"alert":null,"status":"automatic","tsunami":0,"sig":74,"net":"ak","code":"0194a3ew0w","ids":",ak0194a3ew0w,","sources":",ak,","types":",geoserve,origin,","nst":null,"dmin":null,"rms":0.74,"gap":null,"magType":"ml","type":"earthquake","title":"M 2.2 - 84km SSE of Old Iliamna, Alaska"},"geometry":{"type":"Point","coordinates":[-154.542,59.0119,127.6]},"id":"ak0194a3ew0w"},

{"type":"Feature","properties":{"mag":1.1,"place":"107km W of Cantwell, Alaska","time":1554313769466,"updated":1554313953376,"tz":-540,"url":"https://earthquake.usgs.gov/earthquakes/eventpage/ak0194a3e7ki","detail":"https://earthquake.usgs.gov/fdsnws/event/1/query?eventid=ak0194a3e7ki&format=geojson","felt":null,"cdi":null,"mmi":null,"alert":null,"status":"automatic","tsunami":0,"sig":19,"net":"ak","code":"0194a3e7ki","ids":",ak0194a3e7ki,","sources":",ak,","types":",geoserve,origin,","nst":null,"dmin":null,"rms":0.63,"gap":null,"magType":"ml","type":"earthquake","title":"M 1.1 - 107km W of Cantwell, Alaska"},"geometry":{"type":"Point","coordinates":[-151.0662,63.2378,7.8]},"id":"ak0194a3e7ki"},

我试过:

JsonArray jsonObject = new JsonParser()
                    .parse(result)
                    .getAsJsonArray();
List<String> names = new ArrayList<>();
for (JsonElement jsonElement : jsonObject) {
    names.add(jsonElement.getAsJsonObject().get("properties").getAsString());

如果您在 JavaEE 项目中,您可以开始,但如果您在 JavaSE 项目中,则需要添加这些依赖项。

例如使用maven:

<dependencies>
        <dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>javax.json</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-client</artifactId>
            <version>2.25.1</version>
        </dependency>
</dependencies>

这是代码:

  • 第一行,呼叫您的url。
  • 第二行,将响应处理为 json。
public void loadData() {
        Response response = ClientBuilder.newClient().target("https://earthquake.usgs.gov")
                .path("/fdsnws/event/1/query")
                .queryParam("format", "geojson")
                .queryParam("eventtype", "earthquake")
                .request()
                .get();

        Json.createReader((InputStream) response.getEntity())
                .readObject().getJsonArray("features")
                .stream()
                .map(JsonValue::asJsonObject)
                .map(jsonObject -> jsonObject.getJsonObject("properties"))
                .forEach(System.out::println);
}

如您所见,此代码在屏幕上打印名为 "properties" 的数组中名为 "features" 的每个 JsonObject。

重要提示:请注意,您在问题中提供的字符串示例无效 [​​=33=]。使用 url.

返回的那个

earthquake.usgs.gov API returns payload in GeoJSON format. There is geogson 实现所有需要的适配器的库。您只需要添加依赖项:

<dependency>
   <groupId>com.github.filosganga</groupId>
   <artifactId>geogson-core</artifactId>
   <version>1.2.21</version>
</dependency>

您可以在下面找到如何使用它的简单示例:

import com.github.filosganga.geogson.gson.GeometryAdapterFactory;
import com.github.filosganga.geogson.model.FeatureCollection;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class GsonApp {

    public static void main(String[] args) throws Exception {
        URL url = new URL("https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&eventtype=earthquake");
        URLConnection yc = url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));

        Gson gson = new GsonBuilder()
                .registerTypeAdapterFactory(new GeometryAdapterFactory())
                .create();

        FeatureCollection collection = gson.fromJson(in, FeatureCollection.class);
        collection.features().forEach(f -> {
            System.out.println(f.properties());
        });
    }
}

以上应用打印:

null, cdi=null, url="https://earthquake.usgs.gov/earthquakes/eventpage/us1000jimv", ids=",us1000jimv,", time=1552230050190, detail="https://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us1000jimv&format=geojson", updated=1553025676040, status="reviewed"}
{dmin=0.01354, code="73150236", sources=",nc,", tz=-480, mmi=null, type="earthquake", title="M 0.3 - 8km WNW of Cobb, CA", magType="md", nst=10, sig=2, tsunami=0, mag=0.32, alert=null, gap=159, rms=0.02, place="8km WNW of Cobb, CA", net="nc", types=",geoserve,nearby-cities,origin,phase-data,scitech-link,", felt=null, cdi=null, url="https://earthquake.usgs.gov/earthquakes/eventpage/nc73150236", ids=",nc73150236,", time=1552229803430, detail="https://earthquake.usgs.gov/fdsnws/event/1/query?eventid=nc73150236&format=geojson", updated=1552436044263, status="reviewed"}
{dmin=0.0134, code="73150231", sources=",nc,", tz=-480, mmi=null, type="earthquake", title="M 0.6 - 8km WNW of Cobb, CA", magType="md", nst=9, sig=5, tsunami=0, mag=0.57, alert=null, gap=152, rms=0.01, place="8km WNW of Cobb, CA", net="nc", types=",geoserve,nearby-cities,origin,phase-data,scitech-link,", felt=null, cdi=null, url="https://earthquake.usgs.gov/earthquakes/eventpage/nc73150231", ids=",nc73150231,", time=1552229731210, detail="https://earthquake.usgs.gov/fdsnws/event/1/query?eventid=nc73150231&format=geojson", updated=1552235523281, status="automatic"}
....