首页 > 解决方案 > 改造自动解析html unicode

问题描述

我有个问题。我有一个json。我正在尝试解析 和 之类的'符号\u00e7。Symbol\u00e7解析成功,但 symbol'保持不变。这是我的改造建造者。

Retrofit.Builder()
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .baseUrl(RatersApi.BASE_URL)
        .client(get())
        .build()
        .create(RatersApi::class.java)

以及从get()函数调用的 ok http builder

OkHttpClient.Builder()
        .addInterceptor(HttpLoggingInterceptor()
            .apply { level = HttpLoggingInterceptor.Level.BODY }
        )
        .addInterceptor(HeaderInterceptor())
        .build()

回答

行。我没有找到正确的解决方案,所以我编写了自己的拦截器来从 html 转换字符串。只需将其注入您的okhttp构建器即可:

class HtmlStringInterceptor: Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val response = chain.proceed(chain.request())

        val contentType = response.body?.contentType()
        val bodyString = if (android.os.Build.VERSION.SDK_INT >= 24) {
            Html.fromHtml(response.body?.string(), Html.FROM_HTML_MODE_COMPACT).toString()
        } else {
            Html.fromHtml(response.body?.string()).toString()
        }

        val body = bodyString.toResponseBody(contentType)
        return response.newBuilder().body(body).build()
    }
}

标签: androidkotlinretrofitunicode-string

解决方案


此问题的原因已在您的标题中:'是 HTML 代码而不是 Unicode。

所以 JSON 解析是正确的,你需要额外的处理来处理 HTML 内容。例如,如果您想在 TextView 中显示它,您可以使用以下内容:

// extension function to handle different api levels 
fun TextView.setHtml(htmlContent: String) {
    if (android.os.Build.VERSION.SDK_INT >= 24) {
        this.text = Html.fromHtml(htmlContent, Html.FROM_HTML_MODE_COMPACT)
    } else {
        @Suppress("DEPRECATION")
        this.text = Html.fromHtml(htmlContent)
    }
}

// set view content from JSON 
text_view.setHtml("test: '")

推荐阅读