2016-02-12 141 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();