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>





郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。