1. 程式人生 > >Android網絡請求與數據解析,使用Gson和GsonFormat解析復雜Json數據

Android網絡請求與數據解析,使用Gson和GsonFormat解析復雜Json數據

byte 自動 content json對象 .sh cimage 超文本 getjson puts

版權聲明:未經博主允許不得轉載

技術分享圖片

一:簡介

【達叔有道】軟件技術人員,時代作者,從 Android 到全棧之路,我相信你也可以!閱讀他的文章,會上癮!You and me, we are family !

二:前言

在開發中我們要面對很復雜的操作,那麽今天的網絡請求與數據解析也是對於學習Android開發者來說,需要解決的難題,我只是講解一下知識內容,用於理解這方面的知識點。

三:HttpUrlConnection和JSON數據解析

網絡請求有兩種類型,一個是get,另一個是post。網絡請求通常使用HttpUrlConnction,HttpClient,還有更多的框架使用,這些框架也是其他人自己開發出來便於使用的。

對於json解析,官方的原生解析和Gson解析,JSON是一種輕量級的數據交換格式,有很好的可讀性和快速編寫的特點。建議你可以下載一個Google插件,JSON Viewer可以便於看起來舒服點。

看看JSON數據api: https://www.sojson.com/open/api/weather/json.shtml?city=%E4%B8%8A%E6%B5%B7

在你的Android Studio中也提供一個插件名為:GsonFormat,GsonFormat可以幫你格式化Json數據,並自動生成相應的屬性類。這個插件是不是很好,那就下載吧,如果項目巨大,你的Json數據多到你也不想打代碼了吧!

下載完Android Studio中的插件時(過程可以百度)重新啟動一下就行。我們來驗證是否安裝成功,找個java文件按alt+S,彈出GsonFormat的窗口則代表安裝成功。

在GsonFormat中,放入https://www.sojson.com/open/api/weather/json.shtml?city=%E4%B8%8A%E6%B5%B7(復制全部放入),點擊Format即可。

有了GsonFormat的功能,我們就不用辛苦生成Json數據裏的屬性類。

四:使用json解析

JSON數據一般由服務器端提供接口,我們根據接口地址解析數據,然後把數據顯示在APP上。

舉例:接口地址

多個數據
{
‘students‘:[
{‘id‘:‘1‘,
‘name‘:‘peipei‘,
‘sex‘:‘男‘},
{‘id‘:‘2‘,
‘name‘:‘kebin‘,
‘sex‘:‘男‘},
{‘id‘:‘3‘,
‘name‘:‘hong‘,
‘sex‘:‘女‘},
]
}
private void parseJson(String strResult){
 try{
  JSONArray obj = new JSONObject(strResult).getJSONArray("students");
  String s="";
  for(int i=0;i<obj.length();i++){
    JSONObject json = (JSONObject)obj.get(i);
    int id = json.getInt("id");
    String name=json.getString("name");
    String sex=json.getString("sex");
   s+="Id號:"+id+",名字:"+name+",性別:"+sex+"\n";
  }
   
}catch(JSONException e){
 e.printStackTrace();
}

如果這樣寫我的天,也是挺累,對於使用Gson來說就很方便啦。待會我來講使用方法。

對於Android來說重要的網絡部分,如何解決從網絡上下載數據,如何解決上傳,等。我們開發app會不斷向服務器發送請求,那麽返回到APP的是json數據的字符串,我們需要對json數據進行解析才能顯示到app客戶端上。對於HTTP協議是這樣的,http為超文本傳送協議,是web的基礎,http是建立在tcp上的一種。http在客戶端發送請求都要服務器回送響應,請求結束後,會主動釋放。這個過程連接到關閉為一次連接。

五:網絡權限

在我們使用網絡請求的時候,需要的是設置權限,這一點千萬別忘記了。

<uses-permission android:name="android.permission.INTERNET"/>

六:使用Gson

Gson就是一個jar包,導入就行,源代碼可以看看:https://github.com/google/gson
我們只要在build.gradle的dependencies下
放入代碼:

implementation ‘com.google.code.gson:gson:2.2.4‘
//我的是導入的

我們來使用這個接口試試:https://www.sojson.com/open/api/weather/json.shtml?city=%E5%B9%BF%E5%B7%9E
使用Gson,解析

public static WeatherBean getWeather(String res) {
//創建Gson對象
Gson gson =new Gson();
//gson.fromJson(參數1,參數2);
WeatherBean wetherBean = gson.fromJson(res, WeatherBean.class);
//返回
return wetherBean;
}

七:比較詳細地說明

//HttpUrlConnection
//1.實例化一個URL的對象
//2.獲取HttpUrlConnection對象
//3.設置請求連接的屬性
//4.獲取響應碼,判斷是否連接成功
//5.讀取輸入流並解析

八:

要創建一個子線程

new Thread(){
 @Override
 public void run(){
  try{
URL url = new URL(“api地址”);
HttpURLConnection coon=(HttpURLConnection)url.openConnection();
coon.setRequestMethod(“GET”);
coon.setReadTimeout(6000);
//獲取響應碼
If(coon.getResponseCode()==200){
  InputStream in=coon.getInputStream();
  byte[] b = new byte[1024*512];
  int len=0;
  //建立緩存流,保存所讀取的字節數組
  ByteArrayOutputStream baos = new ByteArrayOutputStream();

  while((len=in.read(b))>-1){
    baos.write(b,0,len);   
  }
  String msg = baos.toString();
  Log.e(“TAG”,msg);

  //JSON數據的解析:1.原生解析2.gson解析
  JSONObject obj = new JSONObject(msg);//捕獲異常
  
  int dui = obj.getInt("dui");
  String msg2 = obj.getString("msg");

  Log.e("TAG,"+dui+" "+msg2);
  
  JSONObject data = obj.getJSONObject("data");
  String title = data.getString("title");
  String author = data.getString("author");
  String content = data.getString("content");
  Log.e("TAG","標題:"+title+",作者"+author+",內容:"+content);

   //顯示 解決問題-將操作權交還給主線程

   Message message = handler.obtainMessage();
   Weather e = new Weather (title,author,content);
   message.obj = e;

   //調用此方法,會觸發主線程中Handler對象裏覆蓋了的handleMessage方法

   handler.sendMessage(message);
   //nameView.setText(title);
   //authorView.setText(author);
   //contentView.setText(content);

}
  }catch(MalformedURLException e){
   e.printStackTrace();
  }catch(IOExeption e){
   e.printStackTrace();
  }catch(JSONException e){
   e.printStackTrace();
  }
 }
}.start();
//Hander hander = new Hander()
這個用來解決主線程和子線程進行交互的問題
//封裝對象
private Hander handler = new Handler(){
 @Override
 public void handleMessage(Message msg){
  super.handleMessage(msg);
   
   //獲取
   Weather e = (Weather)msg.obj;
   nameView.setText(e.getTitle());
   authorView.setText(e.getAuthor());
   contentView.setText(e.getContent());
 
 }
};
//使用Gson解析上一步
//1.創建Gson對象
Gson gson = new Gson();
//參數1:滿足json對象格式的字符串
String data=obj.getString("data");
Weather e = gson.fromJson(data,Weather.class);
//JSONObject jo= new JSONObject(result);
//JSONArray ary = jo.getJSONArray("data");
      
//for(int i=0;i<ary.length();i++){
     //JSONObject obj = ary.getJSONObject(i):
     //String a = obj.getString("name");
//}

private void parseJson(String strResult){
 try{
  JSONArray obj = new JSONObject(strResult).getJSONArray("students");
  String s="";
  for(int i=0;i<obj.length();i++){
    JSONObject json = (JSONObject)obj.get(i);
    int id = json.getInt("id");
    String name=json.getString("name");
    String sex=json.getString("sex");
   s+="Id號:"+id+",名字:"+name+",性別:"+sex+"\n";
  }
   
}catch(JSONException e){
 e.printStackTrace();
}
//比較
String data=new JSONObject(result).getString("data");
//使用Gson
Gson gson = new Gson();
//使用Gson,快速解析,添加jar包
//1.解析普通的json對象
//2.解析json數組
//參數1:滿足json數組形式的字符串
//參數2:Type對象,泛型將會決定,你的json字符串最後被轉化成的類型
ArrayList<對象> objects = gson.fromJson(data,new TypeToken<ArrayList<對象>>(){}.getType());

以上就是個人記錄知識點

編輯 :達叔

定位:分享 Android&Java 知識點

Android網絡請求與數據解析,使用Gson和GsonFormat解析復雜Json數據