GSON – trim string during deserialization from JSON

Tags: , , ,



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 = "{'employee.name':'Bob  ','employee.country':'  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?

Answer

You need to implement custom com.google.gson.JsonDeserializer deserializer which trims String values:

class StringTrimJsonDeserializer implements JsonDeserializer<String> {

    @Override
    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())
        .create();


Source: stackoverflow