How to have Retrofit to unescape HTML escaped symbols?

前端 未结 1 1125
一整个雨季
一整个雨季 2021-01-27 09:24

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

public class RestClientFactory {
    private static GsonBuilder gsonBuilde         


        
1条回答
  •  说谎
    说谎 (楼主)
    2021-01-27 10:20

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

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

    and adding

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

    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.

    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.

    0 讨论(0)
提交回复
热议问题