错误消息:JSONObject文本必须以' {'在1 [字符2行1]

时间:2017-08-01 14:21:04

标签: java json

我试图从Wunderground API获取特定时间的历史温度,并且我收到以下错误。任何帮助将不胜感激!

public static void main(String[] args) throws IOException {
    try {
              String date = "20161211";
                String sURL = "http://api.wunderground.com/api/da7962c092ba005b/history_"
                       + date + "/q/autoip.json";
              URL url = new URL(sURL);
              String temp1 = "";
              URLConnection yc = url.openConnection();
              BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
              String inputLine;

              while ((inputLine = in.readLine()) != null) {
                  JSONObject json = new JSONObject(sURL);
                  temp1 = json.getJSONObject("observations").getString("tempi");
                  System.out.println(temp1);

          }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

我收到以下错误:

org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 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 Weather.main(Weather.java:54)

3 个答案:

答案 0 :(得分:0)

你可能想写:

JSONObject json = new JSONObject(inputLine );

而不是:

JSONObject json = new JSONObject(sURL);

但它仍然不正确 - 您必须从InputStream(所有行)读取整个String,然后才构造JSONObject(一次,不在循环中)。

答案 1 :(得分:0)

有几件事。

首先,你的json对象是获取url,而不是响应。

JSONObject json = new JSONObject(sURL);

对于Json,你不能逐行解析,你需要获得整个响应。

响应应该是这样的:

yc.getContent()  

当您获得输入流时,您尝试将值传递给URL,而不是返回结果。

答案 2 :(得分:0)

如果你得到JSONObject文本必须以'{'异常开头。然后首先检查传递给JSONObject构造函数的内容。

您应该传递正确的json.txt文件。所以要确保你传递给jsonobject。

String request = FileUtils.readFileToString(new file(“/ home / achaure / Downloads / Amol / KountRestTest / Documents / request.txt”));

JSONObject jsonObject = new JSONObject(request);

相关问题