Skip to content

GSON – trim string during deserialization from JSON

I have a JSON string that is parsed using the GSON library into a Map like so:

static Type type = new TypeToken<Map<String, String>>() {}.getType();
// note the trailing/leading white spaces
String data = "{'':'Bob  ','':'  Spain  '}";

Map<String, String> parsedData = gson.fromJson(data, type);

The problem I have is, my JSON attribute values have trailing/leading whitespaces that needs to be trimmed. Ideally, I want this to be done when the data is parsed to the Map using GSON. Is something like this possible?



You need to implement custom deserializer which trims String values:

class StringTrimJsonDeserializer implements JsonDeserializer<String> {

    public String deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        final String value = json.getAsString();
        return value == null ? null : value.trim();

And, you need to register it:

Gson gson = new GsonBuilder()
        .registerTypeAdapter(String.class, new StringTrimJsonDeserializer())