如何进行翻新以使HTML转义的符号转义? [英] How to have Retrofit to unescape HTML escaped symbols?

查看:109
本文介绍了如何进行翻新以使HTML转义的符号转义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use Retrofit2 and GSON to deserialize incoming JSON. Here is my code in Android app:

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转义的符号,例如& 改装并不会使其逃脱.

If in incoming JSON are any HTML escaped symbols, e.g. & Retrofit is not unescaping it.

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

E.g. when incoming json has text:

健康& amp;健身

Healh & Fitnesss

按原样反序列化.

但是我需要得到这个:

健康&健身

Healh & Fitnesss

如何使Retrofit自动取消对HTML转义的合成符号的转义?

How can I get Retrofit to automatically unescape HTML escaped synbols?

推荐答案

作为通用答案,可以使用自定义 JsonDeserialiser 完成,例如:

As a generic answer this could be done with custom JsonDeserialiser, like:

public class HtmlAdapter implements JsonDeserializer<String> {

    @Override
    public String deserialize(JsonElement json, Type typeOfT, 
                                  JsonDeserializationContext context)
        throws JsonParseException {
        return StringEscapeUtils.unescapeHtml4(json.getAsString());
    }

}

并添加

gsonBuilder.registerTypeAdapter(String.class, new HtmlAdapter())

到您的静态块.方法 StringEscapeUtils.unescapeHtml4 来自外部库 org.apache.commons,commons-text ,但是您可以用任何感觉更好的方法来实现.

to your static block. Method StringEscapeUtils.unescapeHtml4 is from external library org.apache.commons, commons-text but you can do it with any way you feel better.

该特定适配器的问题是,它适用于所有反序列化的 String 字段,并且可能会或可能不会导致性能问题.

The problem with this particular adapter is that it applies to all deserialized String fields and that may or may not be a performance issue.

要获得更复杂的解决方案,您还可以查看

To have a more sophisticated solution you could also take a look at TypeAdapterFactory. With that you can decide per class if you want apply some type adapter to that class. So if for example your POJOs inherit some common base class it would be simple to check if class extends that base class and return adapter like HtmlAdapter to apply HTML decoding for Strings in that class.

这篇关于如何进行翻新以使HTML转义的符号转义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆