android - 改造自动解析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()
}
}
解决方案
此问题的原因已在您的标题中:'
是 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: '")
推荐阅读
- c - 正则表达式匹配错误的字符串
- mongodb - mongodb findAndModify (upsert) 如果文档不存在则插入字段但如果文档正在更新则不更新字段
- scala - CrossValidator 不支持 VectorUDT 作为 spark-ml 中的标签
- sap-cloud-sdk - 更新请求不再将所有字段发送到 SAP S/4HANA 系统
- xml - XSLT 多个输出文件不适用于命名空间
- excel - 根据相似的单元格值添加单元格
- python - 在 Python 游戏中,“while”和变量的输出不正确
- java - 如何克服与“visibilityOfElementLocated”代码块相似的问题?
- java - 如何在 linux 系统启动脚本中启用 java 路径?
- android-fragments - 如何在支持地图片段上添加当前位置