GSON – 在从JSON反序列化过程中修剪字符串

huangapple go评论113阅读模式
英文:

GSON - trim string during deserialization from JSON

问题

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

static Type type = new TypeToken<Map<String, String>>() {}.getType();
// 注意尾随/前导空格
String data = "{'employee.name':'Bob  ','employee.country':'  Spain  '}";

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

我遇到的问题是,我的JSON属性值具有尾随/前导空格,需要修剪。理想情况下,我希望在数据解析为Map时使用GSON进行修剪。类似这样的操作是否可行?

英文:

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

static Type type = new TypeToken&lt;Map&lt;String, String&gt;&gt;() {}.getType();
// note the trailing/leading white spaces
String data = &quot;{&#39;employee.name&#39;:&#39;Bob  &#39;,&#39;employee.country&#39;:&#39;  Spain  &#39;}&quot;;

Map&lt;String, String&gt; 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?

答案1

得分: 2

你需要实现自定义的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();
英文:

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

class StringTrimJsonDeserializer implements JsonDeserializer&lt;String&gt; {

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

huangapple
  • 本文由 发表于 2020年10月14日 17:05:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/64349983.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定