1

I'm trying to convert a string (every JSON object is separated by commas, but first JSON object is the description of this collection) with JSON objects to JsonArray and then I'm trying to iterate on some subelement of each JsonElement, but every single attempt ends up with an error.

String example:

{"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"},

I've tried:

JsonArray jsonObject = new JsonParser()
                    .parse(result)
                    .getAsJsonArray();
List<String> names = new ArrayList<>();
for (JsonElement jsonElement : jsonObject) {
    names.add(jsonElement.getAsJsonObject().get("properties").getAsString());
Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
b36
  • 105
  • 1
  • 8
  • Can you post the stackTrace ? – Nilamber Singh Apr 03 '19 at 18:14
  • From this part of code I receive: String result = IOUtils.toString(in, "UTF-8"); JsonArray jsonObject = new JsonParser() .parse(result) .getAsJsonArray(); Error: java.lang.IllegalStateException: This is not a JSON Array. – b36 Apr 03 '19 at 18:17
  • Your string example is not a proper `JSON Object`. Refer to this probably you will find an answer [https://stackoverflow.com/questions/22687771/how-to-convert-jsonobjects-to-jsonarray] – Nilamber Singh Apr 03 '19 at 18:21
  • Read the file into a `String`, split it on the delimiter, parse each piece into a `JsonObject`, and add parsed object to a preexisting `JsonArray`. – The Head Rush Apr 03 '19 at 18:23
  • I've used this url to retrieve JSON object that I'm using in this solution: https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&eventtype=earthquake – b36 Apr 03 '19 at 18:24
  • It should be validated in this url. – b36 Apr 03 '19 at 18:32

2 Answers2

0

In case you are in a JavaEE project you are good to go, but if you are in a JavaSE project you need to add these dependencies.

For example, using 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>

And here it is the code:

  • First line, calling your url.
  • Second line, processing response as 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);
}

As you can see this code prints on screen every single JsonObject called "properties" inside an array called "features".

Important: Be aware that string example you gave in your question is not a valid JSON. Use the one returned by url.

Pablo AM
  • 294
  • 1
  • 10
  • Hi, thank you very much for your exhausting reply. Could you please advice how to resolve ClientBuilder Cannot resolve symbol 'ClientBuilder') and response.getEntity() ("Cannot resolve method 'getEntity()") within these libraries? I have added deps in pom.xml and added jar files according to provided realeses. Thank you in advance. – b36 Apr 03 '19 at 21:04
  • Ok, it has been resolved, but when I try to run it there is an error: Exception in thread "main" java.lang.RuntimeException: java.lang.ClassNotFoundException: org.glassfish.jersey.client.JerseyClientBuilder at javax.ws.rs.client.ClientBuilder.newBuilder(ClientBuilder.java:110) at javax.ws.rs.client.ClientBuilder.newClient(ClientBuilder.java:121) at retrieveEarthquakeData.postJSON(retrieveEarthquakeData.java:24) at showEarthquakes.main(showEarthquakes.java:3) Caused by: java.lang.ClassNotFoundException: ... – b36 Apr 03 '19 at 22:00
  • @b36 I have just updated my answer with a different dependency, try it out and see if solves that error. In my test is working fine. Cheers! – Pablo AM Apr 04 '19 at 13:06
  • Hi, still the same error occuring. I've tried to resolve, but no effect. – b36 Apr 04 '19 at 17:29
0

earthquake.usgs.gov API returns payload in GeoJSON format. There is geogson library which implements all needed adapters. You need to only add dependency:

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

and below you can find simple example how to use it:

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());
        });
    }
}

Above app prints:

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"}
....
Community
  • 1
  • 1
Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
  • Hi Michał, thank you very much for the reply. but I've got an error in f.properties(): Error:(26, 39) java: cannot access com.google.common.collect.ImmutableMap class file for com.google.common.collect.ImmutableMap not found – b36 Apr 04 '19 at 17:27
  • @b36, you need to include [Guava: Google Core Libraries For Java](https://mvnrepository.com/artifact/com.google.guava/guava) – Michał Ziober Apr 04 '19 at 17:58
  • 1
    Ok, works with such a dependency: com.google guava 10.0.1-v201203051515 – b36 Apr 04 '19 at 18:12
  • @b36, I'm glad to hear that. For more info how `SO` works take a look on [How does accepting an answer work?](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) – Michał Ziober Apr 04 '19 at 18:31
  • Thanks a lot. Really aprreciate it. – b36 Apr 05 '19 at 19:16