I'm reasonably happy with the execution:
thufir@dur:~/eclipse-workspace/jsr374$
thufir@dur:~/eclipse-workspace/jsr374$ gradle runShadow
> Task :runShadow
Oct 22, 2017 11:59:02 AM net.bounceme.dur.json.JsonOperations tryJsonFromUrl
INFO: https://my-json-server.typicode.com/typicode/demo/db
Oct 22, 2017 11:59:03 AM net.bounceme.dur.json.Main json
INFO: {"posts":[{"id":1,"title":"Post 1"},{"id":2,"title":"Post 2"},{"id":3,"title":"Post 3"}],"comments":[{"id":1,"body":"some comment","postId":1},{"id":2,"body":"some comment","postId":1}],"profile":{"name":"typicode"}}
BUILD SUCCESSFUL in 2s
6 actionable tasks: 1 executed, 5 up-to-date
thufir@dur:~/eclipse-workspace/jsr374$
am less than thrilled with the variable names, error handling, and, specifically, the convertStreamToString
method.
package net.bounceme.dur.json;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import java.util.logging.Logger;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
public class JsonOperations {
private static final Logger LOG = Logger.getLogger(JsonOperations.class.getName());
private JsonObject readJsonFromString(String jsonString) {
JsonReader jsonReader = Json.createReader(new StringReader(jsonString));
JsonObject jsonObject = jsonReader.readObject();
return jsonObject;
}
private String convertStreamToString(InputStream is) {
Scanner scanner = null;
scanner = new java.util.Scanner(is);
scanner = scanner.useDelimiter("\\A");
return scanner.hasNext() ? scanner.next() : "";
}
public JsonObject tryJsonFromUrl(String urlString) {
LOG.info(urlString);
JsonObject jsonObject = null;
try {
jsonObject = jsonFromUrl(urlString);
} catch (IOException e) {
// e.printStackTrace();
LOG.severe(e.toString());
}
return jsonObject;
}
private JsonObject jsonFromUrl(String urlString) throws MalformedURLException, IOException {
LOG.fine(urlString);
InputStream inputStream = new URL(urlString).openStream();
String jsonString = convertStreamToString(inputStream);
inputStream.close();
LOG.fine(jsonString);
JsonObject jsonObject = readJsonFromString(jsonString);
return jsonObject;
}
}
Open, really, to any input. It's meant as a generic sort of utility. Perhaps static methods? Wasn't sure.
Finally, it's perhaps an erroneous assumption that the JSON will come in via URL...
Basically, just want to make it a bit more robust. For example, if there's a problem, pretty much anywhere down the line...perhaps throw a custom exception? Or return a default empty JSON object? Both?
Finally, if there's a library which handles URL -> JSON seamlessly then all the better.