Android利用Gson實現對象和Json數據的相互轉換
MainActitity如下:
package cc.test; import android.app.Activity; import android.os.Bundle; /** * Demo描述: * 利用Gson實現對象和Json數據的相互轉換 * * Demo描述: * 通過一個網絡請求,獲取JSON數據 * * 注意: * 1 網絡請求的參數是JSON格式的數據 * 2 請求結果返回的亦是JSON格式的數據 * */ public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); } private void init(){ new Thread(){ public void run(){ GetJsonDataByPost httpJsonPost=new GetJsonDataByPost(); String[] pathArray=httpJsonPost.getPathArray("dev0003"); for(int i=0;i<pathArray.length;i++){ System.out.println(pathArray[i]); } } }.start(); } }
GetJsonDataByPost如下:
package cc.test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpConnectionParams; import org.apache.http.protocol.HTTP; public class GetJsonDataByPost { static private String Service_URL = "Your url"; static private int TIMEOUT = 120 * 1000; String mMethodName; public String[] getPathArray(String devnum) { try { mMethodName = "GetPicByUser"; String[] pathArray = null; //將調用API的參數封裝成JSON格式 String jsonParams = JsonUtils.getJsonRequestParams(devnum); //返回的JSON數據 String jsonResult = getJsonDataByPost(jsonParams); //從返回的JSON數據獲取其包含的一個數組 pathArray = JsonUtils.getJsonRequestResponse(jsonResult); return pathArray; } catch (Exception e) { e.printStackTrace(); } return null; } public String getJsonDataByPost(String json) { String result = null; try { StringEntity entity = new StringEntity(json, HTTP.UTF_8); entity.setContentType("application/json"); DefaultHttpClient client = new DefaultHttpClient(); client.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, TIMEOUT); client.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, TIMEOUT); if(mMethodName == null){ return null; } HttpPost httpPost = new HttpPost(Service_URL + mMethodName); httpPost.setEntity(entity); HttpResponse response = client.execute(httpPost); InputStream inputStream = response.getEntity().getContent(); StringBuffer buffer = new StringBuffer(); InputStreamReader inputReader = new InputStreamReader(inputStream); BufferedReader bufferReader = new BufferedReader(inputReader); String str = new String(""); while ((str = bufferReader.readLine()) != null) { buffer.append(str); } bufferReader.close(); result = buffer.toString(); System.out.println("---> API的請求結果 result="+result); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } }
JsonUtils如下:
package cc.test; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; public class JsonUtils { //該對象用于封裝請求API的參數. //請求時會將該對象轉換為JSON格式的數據 static class JsonRequestParams { String devsn; int uploadid; float healthScore; } //該對象用于封裝請求API返回后的結果. //即會將JSON格式的數據結果封裝成該對象 static class JsonRequestResult { String resultcode; int uploadid; String[] pics; float beat; String crtime; } //將請求的參數封裝成JSON的格式 public static String getJsonRequestParams(String devnum) { try { JsonRequestParams jsonRequestParams = new JsonRequestParams(); jsonRequestParams.devsn = devnum; jsonRequestParams.uploadid = 0; jsonRequestParams.healthScore = 0.0f; Gson gson = new Gson(); //將對象轉換為JSON數據 String jsonRequestParamsString = gson.toJson(jsonRequestParams); System.out.println("---> 封裝后的API請求參數 jsonRequestParamsString="+jsonRequestParamsString); return jsonRequestParamsString; } catch (Exception e) { e.printStackTrace(); } return null; } public static String[] getJsonRequestResponse(String ret){ try { Gson gson = new Gson(); //將返回的JSON數據轉換為對象JsonRequestResult JsonRequestResult mJsonGetPicResponse = gson.fromJson(ret, JsonRequestResult.class); if(mJsonGetPicResponse.resultcode.contains("ok")){ //從對象中獲取除pics外的各個字段且輸出顯示 System.out.println("---> mJsonGetPicResponse.resultcode="+mJsonGetPicResponse.resultcode); System.out.println("---> mJsonGetPicResponse.beat="+mJsonGetPicResponse.beat); System.out.println("---> mJsonGetPicResponse.uploadid="+mJsonGetPicResponse.uploadid); System.out.println("---> mJsonGetPicResponse.crtime="+mJsonGetPicResponse.crtime); //從對象中獲取pics字段,且返回 return mJsonGetPicResponse.pics; } } catch (JsonSyntaxException e) { e.printStackTrace(); } return null; } }
main.xml如下:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ffffff"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello Everyone" android:layout_centerInParent="true"/> </RelativeLayout>
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!