英文:
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<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?
答案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<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();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论