Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android利用Gson實現對象和Json數據的相互轉換

Android利用Gson實現對象和Json數據的相互轉換

編輯:關於Android編程

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


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如下:




    





  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved