我正在使用 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;
}
}
我期望输出是这样**one two**,但事实并非如此。我究竟做错了什么
青春有我
相关分类