Http獲取Json資料,並用Gson解析
阿新 • • 發佈:2019-01-23
對於http訪問伺服器獲取json資料,每個專案中都需要用到的,json解析,個人覺得簡單的用jsonobject就可以了,但是遇到介面多的專案,資料量比較大用gson比較方便,減去你很大的負擔。
為自己寫部落格,也是一個好習慣(好記性不如亂筆頭)
下載gson-xx.jar 匯入libs包
首先http get,post訪問伺服器獲取json資料
public static String httpGet(String url) { HttpGet httpGet = new HttpGet(url); // 建立一個GET方式的HttpRequest物件 HttpClient httpClient = new DefaultHttpClient(); // 建立一個預設的HTTP客戶端 try { HttpResponse httpResponse = httpClient.execute(httpGet); // 執行GET方式的HTTP請求 int reponseCode = httpResponse.getStatusLine().getStatusCode(); // 獲得伺服器的響應碼 if (reponseCode == HttpStatus.SC_OK) { String strResult = EntityUtils.toString(httpResponse .getEntity()); return strResult; } else { Log.e("httpGet", "GET請求失敗!"); } } catch (Exception e) { e.printStackTrace(); } return null; }
public static String httpPost(String url) throws Exception { // 第1步:建立HttpPost物件 HttpPost httpPost = new HttpPost(url); // 設定HTTP POST請求引數必須用NameValuePair物件 /* * Post運作傳送變數必須用NameValuePair[]陣列儲存 */ List<NameValuePair> params = new ArrayList<NameValuePair>(); NameValuePair paramContent = new BasicNameValuePair( "combatBo.username", "admin"); params.add(paramContent); // 設定HTTP POST請求引數 httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); // 第2步:使用execute方法傳送HTTP POST請求,並返回HttpResponse物件 HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() == 200) { // 第3步:使用getEntity方法獲得返回結果 String result = EntityUtils.toString(httpResponse.getEntity()); return result; } else { Log.e("httpPost", "Post請求失敗!"); } return null; }
第二步,解析Json資料
JsonUtil.java工具類
第三步,需要資料對應的javabean類package com.weihb.httpclient; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class JsonUtil { /** * 將Json解析成類物件 */ public static <T> T getPerson(String jsonString, Class<T> cls) { T t = null; try { Gson gson = new Gson(); t = gson.fromJson(jsonString, cls); } catch (Exception e) { e.printStackTrace(); } return t; } public static <T> List<T> getPersons(String jsonString, Class<T> cls) { List<T> list = new ArrayList<T>(); try { Gson gson = new Gson(); list = gson.fromJson(jsonString, new TypeToken<List<T>>() { }.getType()); } catch (Exception e) { e.printStackTrace(); } return list; } public static List<String> getList(String jsonString) { List<String> list = new ArrayList<String>(); try { Gson gson = new Gson(); list = gson.fromJson(jsonString, new TypeToken<List<String>>() { }.getType()); } catch (Exception e) { // TODO: handle exception } return list; } public static List<Map<String,Object>> listKeyMap(String jsonString){ List<Map<String,Object>> list=new ArrayList<Map<String,Object>>(); try { Gson gson = new Gson(); list = gson.fromJson(jsonString, new TypeToken<List<Map<String,Object>>>() { }.getType()); } catch (Exception e) { // TODO: handle exception } return list; } /** * java物件轉json */ public static String JavaToJson(Object cls) { String str = null; try { Gson gson = new Gson(); str = gson.toJson(cls); } catch (Exception e) { e.printStackTrace(); } return str; } }
按照json的資料結構,把Bean類造好。注意類的巢狀,還有資料型別,實在不行就全用string,這是蠢辦法也是最簡單的辦法
舉個例子:
package com.weihb.httpclient;
import java.io.Serializable;
public class Weather implements Serializable {
/**
* @Fields serialVersionUID :
* {"weatherinfo":{"city":"北京","cityid":"101010100"
* ,"temp1":"22℃","temp2"
* :"9℃","weather":"晴","img1":"d0.gif","img2":"n0.gif","ptime":"11:00"}}
*/
private static final long serialVersionUID = -4518932129666918983L;
private Weatherinfo weatherinfo;
public Weatherinfo getWeatherinfo() {
return weatherinfo;
}
public void setWeatherinfo(Weatherinfo weatherinfo) {
this.weatherinfo = weatherinfo;
}
public class Weatherinfo implements Serializable{
/**
* @Fields serialVersionUID :
*/
private static final long serialVersionUID = 3560815538897448426L;
private String city;
private String cityid;
private String temp1;
private String temp2;
private String weather;
private String img1;
private String img2;
private String ptime;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCityid() {
return cityid;
}
public void setCityid(String cityid) {
this.cityid = cityid;
}
public String getTemp1() {
return temp1;
}
public void setTemp1(String temp1) {
this.temp1 = temp1;
}
public String getTemp2() {
return temp2;
}
public void setTemp2(String temp2) {
this.temp2 = temp2;
}
public String getWeather() {
return weather;
}
public void setWeather(String weather) {
this.weather = weather;
}
public String getImg1() {
return img1;
}
public void setImg1(String img1) {
this.img1 = img1;
}
public String getImg2() {
return img2;
}
public void setImg2(String img2) {
this.img2 = img2;
}
public String getPtime() {
return ptime;
}
public void setPtime(String ptime) {
this.ptime = ptime;
}
@Override
public String toString() {
return "Weatherinfo [city=" + city + ", cityid=" + cityid
+ ", temp1=" + temp1 + ", temp2=" + temp2 + ", weather="
+ weather + ", img1=" + img1 + ", img2=" + img2
+ ", ptime=" + ptime + "]";
}
}
}
接下來的工作就非常簡單了,根據jsonutil.java的方法傳入bean即可,完成解析和轉換成json都無壓力。