android Volley+Gson的使用,androidgson
聽說Volley架構非常好用,今天試了一下post請求,果然如此,因為我傳的是json擷取的也是json所以就寫了一種關於json的請求,其實其他的代碼都差不多.首先要先建立一個全域的變數,請求入隊列使用代碼如下:
public class MyApplication extends Application{
public static RequestQueue requestQueue;
//public static Context context;
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
requestQueue=Volley.newRequestQueue(getApplicationContext());
}
public static RequestQueue getHttpRequestQueue(){
return requestQueue;
}
}
然後開始請求代碼如下:
public class Volley {
public String url="http://api.avatardata.cn/Joke/NewstJoke";
String resultStr;
Gson gson;
public Volley(){
volleyPost();
}
public void volleyPost(){
StringRequest request=new StringRequest(Method.POST,url,new Listener<String>() {
@Override
public void onResponse(String response) {
// TODO Auto-generated method stub
//System.out.println(response.toString());
resultStr=response.toString();
Gson gson=new Gson();
Idiom idiom=gson.fromJson(resultStr, Idiom.class);
System.out.println(idiom);
}
}, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
// System.out.println(error.toString());
resultStr=error.toString();
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
// TODO Auto-generated method stub
Map<String,String> map=new HashMap<String, String>();
map.put("key", "yourkey");
map.put("dtype", "JSON");
map.put("format", "true");
map.put("page", "1");
map.put("rows", "10");
return map;
}
};
MyApplication.getHttpRequestQueue().add(request);
}
}
這樣就可以輕鬆擷取json資料。另外擷取資料如何解析呢? 簡單的json我們直接用android 裡面的jsonObject就可以解決,但是稍微複雜一點,包含數組什麼的那樣的話會很麻煩,不要緊,可以用gson來進行json解析,就是把擷取json串的欄位全部封裝到對象裡面,遇到[ ]就用List,遇到{}就用對象來定義,一層層的封裝,然後執行個體化gson,就可以很容易的擷取到資料。
如下字串,截取不完整:
好吧,就這樣吧,需要代碼的話可以找我。因為我比較懶,所以大家將就點吧,雖然不能看到詳細的代碼,但是方法還是很清楚的瞭解的。
一下是我封裝的兩個類