Skip to content

Instantly share code, notes, and snippets.

@visenger
Created June 6, 2018 12:15
Show Gist options
  • Save visenger/a8314776eee6f75d7bfb6dc1a6ac60b1 to your computer and use it in GitHub Desktop.
Save visenger/a8314776eee6f75d7bfb6dc1a6ac60b1 to your computer and use it in GitHub Desktop.
package de.bhtb.data.formats;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.net.URL;
import java.util.Scanner;
public class ExternalJson {
public static void main(String... args) {
try {
URL url = new URL("http://api.open-notify.org/astros.json");
Scanner scanner = new Scanner(url.openStream());
StringBuilder jsonBuilder = new StringBuilder();
while (scanner.hasNextLine()) {
String str = scanner.next();
jsonBuilder.append(str);
}
String json = jsonBuilder.toString();
Gson gson = new Gson();
JsonElement jsonElement = gson.fromJson(json, JsonElement.class);
JsonObject asJsonObject = jsonElement.getAsJsonObject();
JsonElement number = asJsonObject.get("number");
int numberAsInt = number.getAsInt();
System.out.println("number= " + numberAsInt);
System.out.println(asJsonObject.toString());
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment