Aswin
Aswin

Reputation: 1204

gson + retrofit2 : parse special characters

My response contains special characters like English word syllables (eg. ri,peɪtri'eɪʃʌn) which gson cannot parse them and throws exception with Expected begin_object but was string at line 1 column 199 path $ error message. I tried encoding the response with utf-8 by writing below custom deserializer but did not worked. It is terminated immediately when gson.fromJson() is called.

public class WordResponseDeserializer implements JsonDeserializer<Define> {

@Override
public Define deserialize(JsonElement json, Type typeOfT,
                          JsonDeserializationContext context) throws JsonParseException {
    Log.d(getClass().getSimpleName(), "In Deserialize");
    Gson gson = new Gson();
    String string = json.toString();
    byte[] bytes = string.getBytes();
    String enString = new String(bytes, Charset.forName("UTF-8"));
    Define gDefine = gson.fromJson(enString, Define.class); //Crashing here
    return gDefine;
}
}

Can Gson parse these special characters? What is the possible way?

Upvotes: 0

Views: 993

Answers (1)

Antonio Collazo
Antonio Collazo

Reputation: 21

Change this portion of code:

byte[] bytes = string.getBytes();
String enString = new String(bytes, Charset.forName("UTF-8"));
Define gDefine = gson.fromJson(enString, Define.class); //Crashing here

with this:

byte[] bytes = string.getBytes("ISO-8859-1");
String enString = new String(bytes, Charset.forName("UTF-8"));
Define gDefine = gson.fromJson(enString, Define.class);

Upvotes: 1

Related Questions