在我的代码中点击异常,以便在URI上使用JSON
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();
}
例外情况如下......
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)
我可以选择哪种方法适合吗?
答案 0 :(得分:1)
确保使用正确的字符集正确读取InputStream,例如:
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);
}
}
之后你可以使用它:
tokener = new JSONTokener(textBuilder.toString());
JSONObject root = new JSONObject(tokener);