如何让 Retrofit 对 HTML 转义符号进行转义?

我使用 Retrofit2 和 GSON 来反序列化传入的 JSON。这是我在 Android 应用程序中的代码:


public class RestClientFactory {

    private static GsonBuilder gsonBuilder = GsonUtil.gsonbuilder;

    private static Gson gson;

    private static OkHttpClient.Builder httpClient;

    private static HttpLoggingInterceptor httpLoggingInterceptor 

        = new HttpLoggingInterceptor()

            .setLevel(HttpLoggingInterceptor.Level.BASIC);


    static {

       gsonBuilder.setDateFormat(DateUtil.DATETIME_FORMAT);

        httpClient = new OkHttpClient.Builder();

        gson = gsonBuilder.create();

    }


    private static Retrofit.Builder builder = new Retrofit.Builder()

            .baseUrl(BuildConfig.API_BASE_URL)

            .addConverterFactory(GsonConverterFactory.create(gson))

            .client(httpClient.build());


    private static Retrofit retrofit = builder.build();

}

如果传入的 JSON 中有任何 HTML 转义符号,例如&Retrofit 不会对其进行转义。


例如,当传入的 json 有文本时:


健康& 健身


它按原样反序列化。


但我需要得到这个:


健康与健身


如何让 Retrofit 自动取消转义 HTML 转义符?


PIPIONE
浏览 289回答 1
1回答

开满天机

作为通用答案,这可以通过 custom 完成JsonDeserialiser,例如:public class HtmlAdapter implements JsonDeserializer<String> {&nbsp; &nbsp; @Override&nbsp; &nbsp; public String deserialize(JsonElement json, Type typeOfT,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; JsonDeserializationContext context)&nbsp; &nbsp; &nbsp; &nbsp; throws JsonParseException {&nbsp; &nbsp; &nbsp; &nbsp; return StringEscapeUtils.unescapeHtml4(json.getAsString());&nbsp; &nbsp; }}并添加gsonBuilder.registerTypeAdapter(String.class, new HtmlAdapter())到您的静态块。方法StringEscapeUtils.unescapeHtml4来自外部库,org.apache.commons, commons-text但你可以用任何你感觉更好的方式来做。这个特定适配器的问题在于它适用于所有反序列化的String字段,这可能是也可能不是性能问题。要获得更复杂的解决方案,您还可以查看TypeAdapterFactory. 有了它,您可以决定每个类是否要将某种类型适配器应用于该类。因此,例如,如果您的 POJO 继承了一些公共基类,那么检查类是否扩展了该基类并返回适配器就像在该类中HtmlAdapter为Strings应用 HTML 解码一样简单。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java