从 Java 中 Android 的 JSON 响应中解码转义的 HTML 标记

Decode escaped HTML markup from JSON response on Android in Java

我正在尝试解码我​​的 android 应用接收到的 JSON 属性 作为转义 HTML。我在最新的 Android Studio IDE (2.2) 上使用 Java 8,但找不到来自 Google 的 Android 库或现有的 java 可以帮助我解决这个问题的代码。

我不想剥离 HTML,我想取消转义 HTML,然后在 TextView 中完整显示 HTML。有很多方法可以正确显示 HTML,但到目前为止只有一种方法可以通过我在 GitHub 上找到的名为 Unbescape 的库从转义字符串中提取 HTML。我希望我不必包括图书馆,因为我只有一个 JSON 属性 可以应对,这看起来有点过分了。

JSON 属性 被接收为:

"HTML": "\u003cp\u003e\u003cu\u003e\u003cstrong\u003eAnother 消息\u003c/strong\u003e\u003c/u\u003e\u003c/p\u003e\n\n\u003cp\u003e\u0026#160;\u003c/p\u003e\n\n\u003ctable border=\"1\" cellpadding=\"1\" cellspacing=\"1\" style=\"width:100%\"\u003e\n\t\u003ctbody\u003e\n\t\t\u003ctr\u003e\n\t\t\t\u003ctd\u003easdf\u003c/td\u003e\n\t\t\t\u003ctd\u003easdfa\u003c/td\u003e\n\t\t\u003c/tr\u003e\n\t\t\u003ctr\u003e\n\t\t\t\u003ctd\u003easdf\u003c/td\u003e\n\t\t\t\u003ctd\u003easdfa \u003c/td\u003e\n\t\t\u003c/tr\u003e\n\t\t\u003ctr\u003e\n\t\t\t\u003ctd\u003easdfa\u003c/td\u003e\n\t\t\t\u003ctd\u003esdfasd\u003c/td\u003e\n\t\t\u003c/tr\u003e\n\t\u003c/tbody\u003e\n\u003c/table\u003e\n\n\u003cp\u003e\u0026#160;\u003c/p\u003e\n"

如有任何帮助,我们将不胜感激。提前致谢。

假设您显示的是 JSON 对象的 JSON 属性,您可以非常简单地测试 JSON 解析。

创建一个包含内容的文本文件,用 {} 包围使其成为有效的 JSON 对象。

{ "HTML": "\u003cp\u003e\u003cu\u003e\u003cstrong\u003eAnother Message\u003c/strong\u003e\u003c/u\u003e\u003c/p\u003e\n\n\u003cp\u003e\u0026#160;\u003c/p\u003e\n\n\u003ctable border=\"1\" cellpadding=\"1\" cellspacing=\"1\" style=\"width:100%\"\u003e\n\t\u003ctbody\u003e\n\t\t\u003ctr\u003e\n\t\t\t\u003ctd\u003easdf\u003c/td\u003e\n\t\t\t\u003ctd\u003easdfa\u003c/td\u003e\n\t\t\u003c/tr\u003e\n\t\t\u003ctr\u003e\n\t\t\t\u003ctd\u003easdf\u003c/td\u003e\n\t\t\t\u003ctd\u003easdfa\u003c/td\u003e\n\t\t\u003c/tr\u003e\n\t\t\u003ctr\u003e\n\t\t\t\u003ctd\u003easdfa\u003c/td\u003e\n\t\t\t\u003ctd\u003esdfasd\u003c/td\u003e\n\t\t\u003c/tr\u003e\n\t\u003c/tbody\u003e\n\u003c/table\u003e\n\n\u003cp\u003e\u0026#160;\u003c/p\u003e\n" }

然后运行这段代码,读取文本文件。

正如您在下面看到的,JSON 解析器会为您取消转义。

public class Test {
    @SerializedName("HTML")
    String html;
    public static void main(String[] args) throws Exception {
        Gson gson = new GsonBuilder().create();
        try (Reader reader = new FileReader("test.json")) {
            Test test = gson.fromJson(reader, Test.class);
            System.out.println(test.html);
        }
    }
}

输出

<p><u><strong>Another Message</strong></u></p>

<p>&#160;</p>

<table border="1" cellpadding="1" cellspacing="1" style="width:100%">
    <tbody>
        <tr>
            <td>asdf</td>
            <td>asdfa</td>
        </tr>
        <tr>
            <td>asdf</td>
            <td>asdfa</td>
        </tr>
        <tr>
            <td>asdfa</td>
            <td>sdfasd</td>
        </tr>
    </tbody>
</table>

<p>&#160;</p>