【问题标题】:Android JSON parsing with HTML tags使用 HTML 标签解析 Android JSON
【发布时间】: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


【解决方案1】:

我使用这种方法从 JSON responsehtml 中剥离 HTML:How to strip or escape html tags in Android

public String stripHtml(String html)
{
    return Html.fromHtml(html).toString();
}

然后检索 JSONArray 而不是 Object

HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity); 
String noHTML = stripHtml(data);

JSONArray jsonArray = new JSONArray(noHTML);

for(int i = 0; i < jsonArray.length(); i++)
 {
     StopInfo stops = new StopInfo();
     JSONObject jsonObject = jsonArray.getJSONObject(i);

     stops.id = jsonObject.getString("ID");
     stops.name = jsonObject.getString("Name");
     stops.lat = jsonObject.getLong("Lat");
     stops.lng = jsonObject.getLong("Long");
     stops.sms = jsonObject.getString("Sms");

     stopArrayList.add(stops);
 }

【讨论】:

    【解决方案2】:

    您可以将其作为对服务器的 http 请求执行,请在单独的线程中执行它(可能是异步任务)。

        HttpClient client = new DefaultHttpClient();
        HttpGet getRquest = new HttpGet(urlLink);
        try {
            HttpResponse respnse = client.execute(getRquest);
            StatusLine statusLine = respnse.getStatusLine();
            String responseS = statusLine.getReasonPhrase();
            if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = respnse.getEntity();
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                entity.writeTo(out);
    
                responseS = out.toString();
                out.close();
                out = null;
            }
    

    响应将是您的 json 字符串。 您的响应字符串是 JSONArray 所以

    JSONArray js = new JSONArray(jsonString);
    

    希望有效果

    使用online json parser查看您的 Json 数据

    【讨论】:

      【解决方案3】:

      这是网站故障。 Json 请求不在 html 标签中。但是您可以从请求字符串中轻松替换它。或者你可以像这样使用Jsoup 解析:

      Document doc = Jsoup.Parse(request);
      String parsedrequest = doc.text();
      

      【讨论】:

        【解决方案4】:

        您需要从 HTML 页面中提取 JSON 组件。这种结构的一种方法是:

        // If `html` is the full HTML string
        String json = html.substring(html.indexOf("["), html.lastIndexOf("]") + 1);
        

        【讨论】:

          【解决方案5】:

          您似乎出于某种原因试图解析源代码。

          看看这个link,它将指导您正确解析 JSON 格式的响应。

          【讨论】:

          • 这也是我尝试过的但得到了那个错误:(
          • 你能发布你用来抓取和解析响应的代码吗?如果您获取 HTML 标记,您会以某种方式获取页面源代码,而不是实际内容。
          • 嗨,我已经编辑了我的帖子以显示我从示例中所做的事情
          猜你喜欢
          • 2014-07-16
          • 1970-01-01
          • 1970-01-01
          • 2019-11-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-09-11
          • 1970-01-01
          相关资源
          最近更新 更多