【问题标题】:Org.json.JSONException: Unterminated string at characterOrg.json.JSONException:字符处未终止的字符串
【发布时间】:2016-02-12 16:39:26
【问题描述】:

通过传递字符串创建 JSONObject 时出现错误。

Org.json.JSONException: Unterminated string at character

我的 JSON 字符串是:

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

这似乎只发生在我在 Windows 中开发的 Linux 上,并且运行良好。此外,问题似乎源于字符串太长。我将数组削减了一半以上,问题就消失了。

我可以做些什么来解决这个问题或者是否有解决方法?

【问题讨论】:

  • 你从哪里得到字符串?字符串可能在 传递给 JSON 库之前被缩短
  • 好吧 rec1 不是有效的 JSON。请提供一个简短但完整的示例来说明问题 - 并说明您如何获取字符串,这很可能是导致问题的原因。
  • 我正在使用这个 1-liner String jsonString = new Scanner(new File(source)).useDelimiter("\\Z").next();从文件中读取它
  • 如果在解析之前打印字符串,是否会缩短?如果没有,你可能想用另一个 JSON 库来测试它,比如 Google 的 Gson。 @JonSkeet 你怎么在 Stack Overflow 上如此无所不在?

标签: java org.json jsonexception


【解决方案1】:

如果您在 Android Studio 中使用 AsyncTask 以咨询 mysql 中的 HttpURLConnectionin 或其他数据库的 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();
        }
    }
}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2019-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-22
      • 1970-01-01
      • 1970-01-01
      • 2013-10-16
      相关资源
      最近更新 更多