gson讀取json字串 Gson 中的乙個坑

2021-10-14 00:05:38 字數 1946 閱讀 5073

gson 是谷歌出品的 json 庫,功能強大,也很安全,很少出現安全漏洞,使用的很廣泛。gson 對型別要求的很嚴格,所以才比較少出現安全漏洞。

但 gson 使用起來也比較繁瑣,沒有 fastjson 之類的類庫使用起來那麼簡單,本文介紹一些使用 gson 在處理字串型別時需要注意的事項。

本文基於 gson 2.8.6

先來看段**:

gson gson = new gson();hashmapdata = new hashmap<>();data.put("ray", "jun");string jsonstring = gson.tojson(data);jsonobject jsonobject = gson.fromjson(jsonstring, jsonobject.class);string str = string.valueof(jsonobject.get("ray"));asserttrue((str).equals("jun")); // false
上面的**輸出的結果是false

再看下面的這段**:

gson gson = new gson();hashmapdata = new hashmap<>();data.put("ray", 18);string jsonstring = gson.tojson(data);jsonobject jsonobject = gson.fromjson(jsonstring, jsonobject.class);integer integer = integer.valueof(string.valueof(jsonobject.get("ray")));asserttrue(integer == 18); // true
上面的**輸出的結果是true。這兩段**基本一樣,在結果上卻不同,下面來看看問題出在**。

下面把第一段**中兩個值都列印出來:

string str = string.valueof(jsonobject.get("ray"));system.out.println("jun");system.out.println(str);
jun"jun"
第二個值明顯和預期的不一樣,問題就出在這裡。

jsonobject 的 get 方法返回的是乙個 jsonelement 的型別,jsonobject 也實現了這個型別,是 gson 中所有型別的父類。

在上面的**中,如果直接對 jsonelement 型別使用 string.valueof,就會呼叫 jsonelement 方法的 tostring 方法,大概**如下:

stringwriter stringwriter = new stringwriter();jsonwriter jsonwriter = new jsonwriter(stringwriter);jsonwriter.setlenient(true);streams.write(this, jsonwriter);return stringwriter.tostring();
相當於會把當前的元素放入 stringwriter 中,然後再呼叫 stringwriter 的 tostring 方法,獲得結果。

到這裡都沒有問題,問題的關鍵在於對於字串型別的值,在 jsonelement 中儲存時,會在外面再加上一層引號。

所以字串 "jun" 會被儲存為 ""jun"",所以如果直接使用 tostring 方法獲得值時,字串會多一層引號。

對於其他非字串型別的值,在呼叫 valueof 時,反而可以獲取到正確的值。

但上面的用法其實都是錯誤的,如果需要獲取特定的值,還是應該使用 gson 提供的 getasxx 系列方法。

文 / rayjun

Gson解析json字串

解析傳遞過來的json字串 jsonparser parser new jsonparser jsonobject jsonobj parser.parse strjson getasjsonobject mapmap new hashmap map.put key01 jsonobj.get ke...

Gson 解析複雜json字串

對gson不了解的同學可以先去了解下gson的基本用法 需要解析的json字串如下 result ok 先貼上解析json字串的 public responsedataprovidernetprovicelistdata string result gettype string resultcode...

使用Gson處理json字串

test public void test01 gettype list list gson.fromjson json,type for listlists list 這裡我是把乙個二維陣列處理成立成乙個list 物件 下面是我使用gson將json字串轉換為物件的兩種方式 第一種 public ...