2015-09-10 54 views
1

從URL讀取json數據時出現錯誤。下面是我想要的代碼。請糾正我錯在哪裏。線程「main」中的異常org.json.JSONException:一個JSONObject文本必須以'{'開始,位於1 [character 2 line 1]

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":"[email protected]":""} 

回答

1

您的JSON是不正確的,看到最後一行打開此URL是「OK當

{ 
"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": "[email protected]": "" 
} 
+0

這是一個TYPO,我修好了它 – tom

0

其實我得到」。這就是爲什麼它抱怨你的Json字符串不是以大括號開頭的原因。

+0

是的,當我嘗試以不同的方式它只是顯示的確定。但是當你嘗試用「http://requestb.in/pp1mzapp」打開一個頁面時,它顯示了json objcet – tom

+0

你應該將jsonText的內容打印到控制檯,以確保你實際得到了你期望的Json字符串。 – benohead

0

我看到了問題,我傳遞的URL是獲取HTML頁面,整個頁面而不是響應正文是問題。

相關問題