本文介绍了如何进行翻新以使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:

按原样反序列化.

但是我需要得到这个:

如何使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.

要获得更复杂的解决方案,您还可以查看 TypeAdapterFactory .这样,您就可以决定是否要对每个类应用某种类型适配器的每个类.因此,例如,如果您的POJO继承了一些常见的基类,则检查类是否扩展了该基类并返回适配器(如 HtmlAdapter )以对HTML中的 String 应用HTML解码将非常简单.该课程.

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转义的符号转义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 00:36