【问题标题】:Java/Android how to get JSON from a html response?Java/Android 如何从 html 响应中获取 JSON?
【发布时间】:2014-10-09 12:47:12
【问题描述】:

我从 HttpGet 得到一个 html 响应,响应如下:

<div class="noti-contents">
    <button class="accept-invitation gui-button" data-invite="pi:103158:18:60:114779" data-invite-details='{"f":"103158","p":18,"api":false,"pid":60,"t":114779,"sub":"p10315857a3f8","u":{"id":"103158","name":"xxxxxx","profile_image":"{1}","status":"1"}}'><span>Accept</span></button>
</div>

以上所有代码都存储在一个字符串变量'response'中;但现在在我的应用程序中,我只需要 html 的 JSON 部分:

{"f":"103158","p":18,"api":false,"pid":60,"t":114779,"sub":"p10315857a3f8","u":{"id":"103158","name":"xxxxxx","profile_image":"{1}","status":"1"}}

那么我应该如何解析这个字符串来得到上面唯一的部分呢?

【问题讨论】:

  • 使用jsoup html解析器获取json
  • @Raghunandan 但我认为 jsoup 需要页面的 url 来获取页面的 html,这个问题中的 html 代码作为回复发送给我,我没有这个的 url html,我应该如何使用jsoup来解析这个?
  • 可以解析字符串响应
  • 你得到一个字符串的响应是什么??

标签: java android json html-parsing jsoup


【解决方案1】:

您可以使用 XML Parser 读取 html 并使用 XPath 查询您要查找的值。

XPath 将是

/div/button/@data-invite-details

Java/Android 中有一篇文章解释了如何实现这一点:

How to read xml using xpath in java

【讨论】:

    【解决方案2】:

    查看文档

    http://jsoup.org/apidocs/org/jsoup/Jsoup.html

    可以使用Jsoup解析html

    Document doc = Jsoup.parse("html string");  
    Elements elements = doc.select("button");
    Log.i("..........",""+elements.attr("data-invite-details"));
    

    日志

    08-15 19:16:42.670: I/..........(1612): {"f":"103158","p":18,"api":false,"pid":60,"t":114779,"sub":"p10315857a3f8","u":{"id":"103158","name":"xxxxxx","profile_image":"{1}","status":"1"}}
    

    【讨论】:

    • 哦!!!!多谢!我从未使用过 Jsoup,所以我不知道它是如何工作的。谢谢你的文件!!!
    • @Solorchid 没问题,只要使用上面的,它应该可以正常工作
    【解决方案3】:

    好吧,我回答这个问题有点晚了,但是对于从 Android 中的 html 响应中获取仅 json 字符串有很好的解决方案

    假设你在变量输出中有一个字符串

    output= Html.fromHtml(output).toString();
    output=output.substring(output.indexOf("{"),output.lastIndexOf("}") + 1);
    

    现在输出只包含 json

    JSONObject jsonObject = new JSONObject(output);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多