JSONObject文本必须以2 {字符3第1行的'{'开头

时间:2015-08-28 11:54:25

标签: java json jsonobject

以下程序我试图调用stackexchange api来获取JSON中的响应。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;

import org.json.JSONException;
import org.json.JSONObject;

public class JsonReader {

  private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
      sb.append((char) cp);
    }
    return sb.toString();
  }

  public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
    InputStream is = new URL(url).openStream();
    try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
      String jsonText = readAll(rd);
      JSONObject json = new JSONObject(jsonText);
      return json;
    } finally {
      is.close();
    }
  }

  public static void main(String[] args) throws IOException, JSONException {
    JSONObject json = readJsonFromUrl("https://api.stackexchange.com/2.2/users/4614124?order=desc&sort=reputation&site=stackoverflow");
    System.out.println(json.toString());
  }
}

当我运行这些时,我收到以下错误,但响应对象以{only。

开头
Exception in thread "main" org.json.JSONException: A JSONObject text must begin with '{' at 2 [character 3 line 1]
    at org.json.JSONTokener.syntaxError(JSONTokener.java:432)
    at org.json.JSONObject.<init>(JSONObject.java:184)
    at org.json.JSONObject.<init>(JSONObject.java:310)
    at JsonReader.readJsonFromUrl(JsonReader.java:28)
    at JsonReader.main(JsonReader.java:36)

1 个答案:

答案 0 :(得分:2)

来自网址的响应是使用Gzip压缩的。您需要在读取之前解压缩输入流。这是通过使用GZIPInputStream包装InputStream来完成的。

public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
    InputStream is = new URL(url).openStream();
    GZIPInputStream gis = new GZIPInputStream(is);
    try {
        BufferedReader rd = new BufferedReader(new InputStreamReader(gis, Charset.forName("UTF-8")));
        String jsonText = readAll(rd);
        JSONObject json = new JSONObject(jsonText);
        return json;
    } finally {
        is.close();
    }
}