0

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();
}

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

E.g. when incoming json has text:

Healh & Fitnesss

it is deserialized as is.

But I need to get this:

Healh & Fitnesss

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

pirho
  • 11,565
  • 12
  • 43
  • 70
Alexei
  • 14,350
  • 37
  • 121
  • 240
  • Why do you want Retrofit to do this job? Can you not just unescape string in java after you get it from Retrofit like [here](https://stackoverflow.com/q/994331/6413377)? It is possible, still. – pirho Sep 26 '18 at 16:53
  • I have about 20 Pojos. Every of them Use Retrofit to get response. I wan't to do this in 20 places. I want to this in one place. – Alexei Sep 26 '18 at 18:44

1 Answers1

1

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());
    }

}

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.

pirho
  • 11,565
  • 12
  • 43
  • 70