我正在使用 GSON 将 json 转换为 POJO,但 json 中的键值可能包含空格,我想修剪它们。为此,我编写了一个自定义字符串反序列化器,但这不起作用。这是我想要的:
public class Foo {
public int intValue;
public String stringValue;
@Override
public String toString() {
return "**" + stringValue + "**" ;
}
}
public void testgson()
{
String json = "{\"intValue\":1,\"stringValue\":\" one two \"}";
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(String.class, new StringDeserializer());
Gson gson = gsonBuilder.create();
Foo a = gson.fromJson(json, Foo.class);
System.out.println(a.toString()); //prints ** one two ** instead of **one two**
}
class StringDeserializer implements JsonDeserializer<String>
{
@Override public String deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException
{
String a = json.toString().trim();
System.out.print(a); //prints ** one two **
return a;
}
}
我期望输出为**一二**
,但事实并非如此。我做错了什么
最佳答案
在您的StringDeserializer
中,这个
json.toString()
正在对 JsonElement
调用 toString
,该 JsonElement 具体来说是一个包含文本值的 JsonPrimitive
。 Its toString
implementation返回其内容的 JSON 表示形式,字面意思是字符串 “一二”
。 trim
没有执行您想要的操作,因为该字符串包含在 "
中。
您真正想做的是读取 JSON 元素的内容。您可以使用 JsonElement
的便捷方法之一来完成此操作:getAsString()
。
所以
String a = json.getAsString().trim();
然后会打印出您期望的内容。
关于java - String 类的 Gson 自定义反序列化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58565807/