String class 的 Gson 自定义反序列化器
Gson custom deserializer for String class
我正在使用 GSON 将 json 转换为 POJO,但 json 中的键值可能包含空格,我想 trim 它们。为此,我编写了一个自定义 String 反序列化器,但它不起作用。这是我想要的:
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**
但事实并非如此。我做错了什么
在你的StringDeserializer
中,这个
json.toString()
正在 JsonElement
上调用 toString
,该 JsonElement
特别是包含文本值的 JsonPrimitive
。 Its toString
implementation returns 其内容的 JSON 表示,字面意思是字符串 " one two "
。 trim
没有按照您的意愿行事,因为该字符串包含在 "
.
中
您真正想做的是阅读 JSON 元素的内容。您可以使用 JsonElement
的一种便捷方法来做到这一点:getAsString()
.
所以
String a = json.getAsString().trim();
然后会打印出您所期望的。
我正在使用 GSON 将 json 转换为 POJO,但 json 中的键值可能包含空格,我想 trim 它们。为此,我编写了一个自定义 String 反序列化器,但它不起作用。这是我想要的:
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**
但事实并非如此。我做错了什么
在你的StringDeserializer
中,这个
json.toString()
正在 JsonElement
上调用 toString
,该 JsonElement
特别是包含文本值的 JsonPrimitive
。 Its toString
implementation returns 其内容的 JSON 表示,字面意思是字符串 " one two "
。 trim
没有按照您的意愿行事,因为该字符串包含在 "
.
您真正想做的是阅读 JSON 元素的内容。您可以使用 JsonElement
的一种便捷方法来做到这一点:getAsString()
.
所以
String a = json.getAsString().trim();
然后会打印出您所期望的。