使用Gson解析資料

2021-07-15 16:41:00 字數 1713 閱讀 9730

使用gson解析資料時可以把要解析的內容看作整個物件,然後以物件的形式解析。

但在有些時候,需要對資料某些字段進行判斷,再根據結果進行解析,這時候就需要對解析的內容的某些部分單獨解析。

使用方式如下:

jsonreader reader = new jsonreader(new stringreader(value));

reader.setlenient(true);

jsonobject jsonobject = new jsonparser().parse(reader).getasjsonobject();

以jsonparser.parse的形式,獲取jsonelement物件,再通過getasint,getasjsonarray等的形式便可獲取到要解析的字段。

其中,在new jsonparser().parse()的方法的時候,parse()的引數如果為string字串,在某些情況會出錯。在用公司平板測試時,會偶爾報一些錯誤,但是在手機上則沒有報這些錯誤。使用引數為jsonreader的形式可以避免這些錯誤。

同時,解析內容如果為

,

.....

]}

也會出現解析異常,可以使用以下的形式解析,避免出錯。通過getasjsonarray()獲取到集合物件,再進行解析。

public arraylistgetdatalist(jsonarray jsonarray, classcls) 

} catch (exception e)

return mlist;

}

附:常見的解析形式

/**

* 解析返回字串list集合

* @param jsonstring

* @return

*/public static listgetliststring(string jsonstring) .gettype());

} catch (exception e)

return list;

}

/**

* 解析返回list內嵌map集合

* @param jsonstring

* @return

*/public static list> getlistmap(string jsonstring) .gettype());

} catch (jsonsyntaxexception e)

return list;

}

/**

* 解析list集合

* @param jsonelement

* @param cls

* @return

*/public listgetlistdata(jsonelement jsonelement, classcls) .gettype());

} catch (exception e)

return mlist;

}

public static t gettdata(string jsonstring, classcls)  catch (exception e) 

return t;

}

使用Gson解析json資料

使用gson解析json資料,非常方便,要細心的配置實體類model。比如json字串為 currentpage 1,allnum 30042,maxresult 20 照上面的json資料,model實體類為 public class joke public void setallpages st...

Gson解析json資料

1 解析單個物件 json字串如下 封裝解析的物件 public class nbamatchs public void setformatdate string formatdate public string getdate public void setdate string date pub...

json資料解析(gson)

string json type type new typetoken gettype suppresswarnings unchecked mapdata map new gson fromjson json,type iterator iterator data.entryset iterato...