我正在使用 GSON 將 json 轉(zhuǎn)換為 POJO,但 json 中的鍵值可能包含空格,我想修剪它們。為此,我編寫了一個(gè)自定義字符串反序列化器,但這不起作用。這是我想要的: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**,但事實(shí)并非如此。我究竟做錯(cuò)了什么
1 回答

青春有我
TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超8個(gè)贊
在你的StringDeserializer
,這個(gè)
json.toString()
正在調(diào)用toString
a?JsonElement
,特別是JsonPrimitive
包含文本值的 a 。它的toString
實(shí)現(xiàn)返回其內(nèi)容的 JSON 表示形式,從字面上看就是 String?" one two ?"
。trim
沒(méi)有執(zhí)行您想要的操作,因?yàn)樵?String 包含在"
.
您真正想做的是讀取 JSON 元素的內(nèi)容。您可以使用其中一種JsonElement
方便的方法來(lái)做到這一點(diǎn):getAsString()
。
所以
String?a?=?json.getAsString().trim();
然后會(huì)打印你所期望的內(nèi)容。
添加回答
舉報(bào)
0/150
提交
取消