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

时间:2019-04-03 18:06:45

标签: java json deserialization geojson json-deserialization

我正在尝试将带有JSON对象的字符串(每个JSON对象用逗号分隔,但是第一个JSON对象是该集合的描述)转换为{{1 }},然后尝试对每个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"},

2 个答案:

答案 0 :(得分:0)

如果您在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>

这是代码:

  • 第一行,调用您的网址。
  • 第二行,将响应作为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);
}

如您所见,此代码在名为“功能”的数组中的每个名为“属性”的JsonObject都会在屏幕上打印。

重要:请注意,您在问题中输入的字符串示例不是有效的JSON。使用url返回的那个。

答案 1 :(得分:0)

earthquake.usgs.gov API以GeoJSON格式返回有效载荷。有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"}
....