2016-02-12 138 views
0

通過傳遞字符串創建JSONObject時出現錯誤。Org.json.JSONException:字符未終止字符串

Org.json.JSONException: Unterminated string at character 

我的JSON字符串是:

{"Count":741,"Data":[{rec1....},{rec2...}, etc]} 

這似乎爲我的Windows開發的,它能正常工作在Linux上只發生。此外,這個問題似乎源於字符串太長。我將陣列減半了一半,問題就消失了。

我該怎麼辦才能解決此問題或者是否有解決方法?

+0

你從哪裏得到字符串?有可能將字符串縮短_before_傳遞給JSON庫 –

+0

那麼'rec1'不是有效的JSON。請提供一個簡短但完整的示例來說明問題 - 並解釋如何獲取字符串,這可能會導致問題。 –

+0

我正在使用這個1-liner'String jsonString = new Scanner(new File(source))。useDelimiter(「\\ Z」)。next();' – drum

回答

1

如果您在Android Studio中使用AsyncTask來諮詢HttpURLConnectionin在mysql或其他數據庫的Gestor中。有一種叫做「String downloadUrl(String myurl)」的方法,有一個變量「int len = 500;」要讀取inmputStream中的數據,可以爲需要讀取的數字壓縮器更改此變量。

private String downloadUrl(String myurl) throws IOException { 
    Log.i("URL",""+myurl); 
    myurl = myurl.replace(" ","%20"); 
    InputStream is = null; 
    // Only display the first 500 characters of the retrieved 
    // web page content. 
    <b>int len = 1500; </b> 

    try { 
     URL url = new URL(myurl); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setReadTimeout(10000 /* milliseconds */); 
     conn.setConnectTimeout(15000 /* milliseconds */); 
     conn.setRequestMethod("GET"); 
     conn.setDoInput(true); 
     // Starts the query 
     conn.connect(); 
     int response = conn.getResponseCode(); 
     Log.d("respuesta", "The response is: " + response); 
     is = conn.getInputStream(); 

     // Convert the InputStream into a string 
     String contentAsString = readIt(is, len); 
     return contentAsString; 

     // Makes sure that the InputStream is closed after the app is 
     // finished using it. 
    } finally { 
     if (is != null) { 
      is.close(); 
     } 
    } 
} 
0

@Daniela正確地發現了問題。我使用的是與開發人員android網站中提到的相同的代碼。我的修復如下:

InputStreamReader reader = new InputStreamReader(stream); 
    BufferedReader br = new BufferedReader(reader); 
    StringBuilder sb = new StringBuilder(); 
    String line; 
    while ((line = br.readLine()) != null) { 
     sb.append(line+"\n"); 
    } 
    br.close(); 
    return sb.toString();