Priyath Gregory
Priyath Gregory

Reputation: 987

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 = "{'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?

Upvotes: 4

Views: 1715

Answers (1)

Michał Ziober
Michał Ziober

Reputation: 38655

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

Upvotes: 4

Related Questions