字符串 org.json.JSONException:字符处未终止的对象
Posted
技术标签:
【中文标题】字符串 org.json.JSONException:字符处未终止的对象【英文标题】:String org.json.JSONException: Unterminated object at character 【发布时间】:2019-04-01 18:09:08 【问题描述】:我正在尝试对 json 进行 http 调用,json 很长。
尝试执行此操作时:
JSONObject json = new JSONObject(htmlString);
错误:
at org.json.JSONTokener.syntaxError(JSONTokener.java:449)
at org.json.JSONTokener.readObject(JSONTokener.java:393)
at org.json.JSONTokener.nextValue(JSONTokener.java:100)
at org.json.JSONTokener.readArray(JSONTokener.java:429)
at org.json.JSONTokener.nextValue(JSONTokener.java:103)
W/System.err: at org.json.JSONTokener.readObject(JSONTokener.java:384)
at org.json.JSONTokener.nextValue(JSONTokener.java:100)
at org.json.JSONTokener.readObject(JSONTokener.java:384)
at org.json.JSONTokener.nextValue(JSONTokener.java:100)
at org.json.JSONTokener.readArray(JSONTokener.java:429)
at org.json.JSONTokener.nextValue(JSONTokener.java:103)
at org.json.JSONTokener.readObject(JSONTokener.java:384)
at org.json.JSONTokener.nextValue(JSONTokener.java:100)
at org.json.JSONTokener.readObject(JSONTokener.java:384)
at org.json.JSONTokener.nextValue(JSONTokener.java:100)
at org.json.JSONObject.<init>(JSONObject.java:156)
at org.json.JSONObject.<init>(JSONObject.java:173)
.......
代码:
private class Html extends AsyncTask<Void, Void, Void>
private String url = "https://pastebin.com/raw/2T93TvDU";
private JSONArray array = new JSONArray();
@Override
protected void onPreExecute()
super.onPreExecute();
@Override
protected Void doInBackground(Void... params)
try
Log.v("Class:" + TAG, "doInBackground:" + url);
Document doc = Jsoup.connect(url).get();
String htmlString = doc.toString();
htmlString = htmlString.replaceAll("<html>", "");
htmlString = htmlString.replaceAll("</html>", "");
htmlString = htmlString.replaceAll("<head>", "");
htmlString = htmlString.replaceAll("</head>", "");
htmlString = htmlString.replaceAll("<body>", "");
htmlString = htmlString.replaceAll("</body>", "");
try
Log.v("Class:" + TAG, "Js:" + htmlString);
JSONObject json = new JSONObject(htmlString);
//Object list = json.get("list");
Log.v("Class:" + TAG, "Json:" + json);
catch (JSONException e)
e.printStackTrace();
catch (IOException e)
e.printStackTrace();
return null;
@Override
protected void onPostExecute(Void result)
populateListItem(array);
【问题讨论】:
【参考方案1】:该 URL 上的数据不是 HTML,而是纯 JSON(以 text/plain
发送)。使用connect().get()
将尝试将其转换为 HTML 文档,错误地编码和解码数据并返回错误的结果。而是使用connect().execute().body()
直接获取JSON 字符串。
@Override
protected Void doInBackground(Void... params)
try
String jsonString = Jsoup.connect(url).execute().body();
JSONObject json = new JSONObject(jsonString);
JSONArray list = json.getJSONObject("list").getJSONArray("item");
// now you can use the list
catch (JSONException | IOException e)
e.printStackTrace();
return null;
【讨论】:
以上是关于字符串 org.json.JSONException:字符处未终止的对象的主要内容,如果未能解决你的问题,请参考以下文章