【发布时间】:2023-03-20 23:28:01
【问题描述】:
我想使用 JsonReader 从 android 中 <HTML> 标签内的 url 解析 JSON。我在 Stackoverflow 和 Androud 参考中尝试了多个示例,但我不断收到 org.json.JSONException: Value <!DOCTYPE 错误或 null pointer exception
这是我要解析的 URL:Link
这是我使用此示例的代码:How to parse JSON in Android
getData 类出现 nullpointexception
JSON 解析器类:
public class JSONParser
{
public String json = "";
public InputStream is = null;
public JSONObject jObj = null;
public JSONObject getJSON(String url)
{
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
// return JSON String
return jObj;
}
地图活动:
private void setUpMap()
{
new getData().execute();
}
class getData extends AsyncTask<String, String, String>
{
@Override
protected String doInBackground(String... params)
{
JSONParser jsonParser = new JSONParser();
JSONObject json = jsonParser.getJSON(url);
try
{
String id = json.getString("ID");
String name = json.getString("Name");
long lat = json.getLong("Lat");
long lng = json.getLong("Long");
String sms = json.getString("Sms");
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
}
}
【问题讨论】:
-
JSON Parser仅读取JSON格式的值,否则会引发错误。如果您收到 HTML 标签作为响应,则表示您的 .php 页面中有一些警告或错误..首先你必须解决这个问题,然后它会给你回复JSON格式 -
请提供完整的 logcat...以及您如何解析它。
-
只有我觉得很奇怪,链接返回有效的 JSON,却被包装在一个 html 页面和内容类型设置为 text/html,为什么不直接使用 application/json?我没有看到将其作为 html 响应的好处...
-
我认为页面给你的是 JSONArray 对象而不是 JSONObject 我猜
-
@Preethi Rao,你是对的。它在一个数组中。
标签: android json android-json