GSON - trim 从 JSON 反序列化期间的字符串

GSON - trim string during deserialization from JSON

我有一个 JSON 字符串,使用 GSON 库将其解析为 Map,如下所示:

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

我遇到的问题是,我的 JSON 属性值有 trailing/leading 个需要修剪的空格。理想情况下,我希望在使用 GSON 将数据解析为 Map 时完成此操作。这样的事情可能吗?

您需要实现自定义 com.google.gson.JsonDeserializer 反序列化器,它会修剪 String 值:

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

而且,您需要注册它:

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