【问题标题】:Exception in thread "main" org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]线程“main”org.json.JSONException 中的异常:JSONObject 文本必须以 '{' 在 1 [字符 2 第 1 行] 开头
【发布时间】:2015-12-07 06:18:25
【问题描述】:

从 URL 读取 json 数据时出现错误。下面是我正在尝试的代码。请纠正我哪里出错了。

public class ReadingJsonData {
 public static void main(String[] args) throws JSONException {
 JSONObject json = readJsonFromUrl("http://requestb.in/pp1mzapp");
  }

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.trim());
       return json;
     } finally {
       is.close();
     }
    }

     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();
    }
     }

我的来自 URL 的 Json 对象看起来像

{"FormID":"2095180","UniqueID":"213482652","Name":{"first":"Something","last":"New"},"Date of Birth":"Feb 03, 1926","Last 4 Digits of SSN":"1234","Week Beginning Date":"Jan 01, 2012","Week Ending Date":"Feb 03, 2014","Email":"something.new@something.gov":""} 

【问题讨论】:

    标签: java json url bufferedreader


    【解决方案1】:

    你的Json不正确,看最后一行

    {
    "FormID": "2095180",
    "UniqueID": "213482652",
    "Name": {
        "first": "Something",
        "last": "New"
    },
    "Date of Birth": "Feb 03, 1926",
    "Last 4 Digits of SSN": "1234",
    "Week Beginning Date": "Jan 01, 2012",
    "Week Ending Date": "Feb 03, 2014",
    "Email": "something.new@something.gov": ""
    }
    

    【讨论】:

    • 这是一个错字,我已修复
    【解决方案2】:

    实际上,打开此 URL 时我得到的结果是“好的”。这就是为什么它抱怨您的 Json 字符串不是以大括号开头的原因。

    【讨论】:

    • 是的,当我以不同的方式尝试时,它只是显示正常。但是,当您尝试使用“requestb.in/pp1mzapp”打开页面时,它会显示 json objcet
    • 您应该将 jsonText 的内容打印到控制台,以确保您实际上得到了您期望的 Json 字符串。
    【解决方案3】:

    我看到了问题,我传递的 URL 是获取 HTML 页面,整个页面而不是响应正文,这是问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-06
      • 1970-01-01
      • 1970-01-01
      • 2017-02-20
      • 1970-01-01
      相关资源
      最近更新 更多