Reputation: 371
Hitting exception in my code below for using JSON on a URI
public static String processRestResponse(String language){
URI uri = null;
JSONTokener tokener = null;
try {
uri = new URI("https://api.github.com/search/repositories?q=language:Java");
URL url = uri.toURL();
InputStream inputStream = url.openStream();
tokener = new JSONTokener(inputStream.toString());
JSONObject root = new JSONObject(tokener);
} catch (Exception e) {
e.printStackTrace();
}
Exception as follows...
org.json.JSONException: A JSONObject text must begin with '{' at character 1
at org.json.JSONTokener.syntaxError(JSONTokener.java:410)
at org.json.JSONObject.<init>(JSONObject.java:179)
at Assignment1.processRestResponse(Assignment1.java:48)
at Assignment1.main(Assignment1.java:108)
Is there an alternative approach i can take that would suit?
Upvotes: 0
Views: 1158
Reputation: 144
make sure you read the the InputStream correctly using the right charset, for example like this:
StringBuilder textBuilder = new StringBuilder();
try (Reader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName(StandardCharsets.UTF_8.name())))) {
int c = 0;
while ((c = reader.read()) != -1) {
textBuilder.append((char) c);
}
}
afteron you can use it:
tokener = new JSONTokener(textBuilder.toString());
JSONObject root = new JSONObject(tokener);
Upvotes: 1