Android利用Gson实现对象和Json数据的相互转换

简介: MainActitity如下:package cc.test;import android.app.Activity;import 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<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>




相关文章
|
17天前
|
JSON API 数据安全/隐私保护
深度分析淘宝卖家订单详情API接口,用json返回数据
淘宝卖家订单详情API(taobao.trade.fullinfo.get)是淘宝开放平台提供的重要接口,用于获取单个订单的完整信息,包括订单状态、买家信息、商品明细、支付与物流信息等,支撑订单管理、ERP对接及售后处理。需通过appkey、appsecret和session认证,并遵守调用频率与数据权限限制。本文详解其使用方法并附Python调用示例。
|
19天前
|
JSON API 数据格式
淘宝/天猫图片搜索API接口,json返回数据。
淘宝/天猫平台虽未开放直接的图片搜索API,但可通过阿里妈妈淘宝联盟或天猫开放平台接口实现类似功能。本文提供基于淘宝联盟的图片关联商品搜索Curl示例及JSON响应说明,适用于已获权限的开发者。如需更高精度搜索,可选用阿里云视觉智能API。
|
27天前
|
JSON 缓存 API
淘宝店铺所有商品API,json数据返回
淘宝店铺所有商品API的JSON数据返回通常包含商品的基本信息、动态数据以及分页信息等。以下是一个详细的JSON数据返回示例,以及相关字段的说明
|
19天前
|
JSON 安全 API
Python处理JSON数据的最佳实践:从基础到进阶的实用指南
JSON作为数据交换通用格式,广泛应用于Web开发与API交互。本文详解Python处理JSON的10个关键实践,涵盖序列化、复杂结构处理、性能优化与安全编程,助开发者高效应对各类JSON数据挑战。
98 1
|
19天前
|
JSON 数据挖掘 API
淘宝详情API接口与高级详情API接口用json返回数据区别
淘宝“商品详情API”与“高级商品API”主要区别在于数据深度、字段丰富度及适用场景。前者适用于轻量级导购展示,后者支持详情页展示与深度分析,需根据业务需求选择使用。
|
26天前
|
设计模式 JSON Unix
微店商品详情API接口,json数据返回
微店商品详情API接口的典型JSON返回数据结构说明,基于公开的微店开放平台API文档和常见电商API设计模式整理。实际使用时请以微店官方最新文档为准
|
29天前
|
JSON API 数据格式
淘宝关键词搜索API接口,json数据返回
淘宝关键词搜索API接口允许开发者通过关键词检索商品,并返回符合条件的商品信息,这些信息通常以JSON格式呈现。以下是一个淘宝关键词搜索API接口返回的JSON数据示例及关键字段说明
|
JSON Android开发 数据格式
Android Gson的使用总结
1、概念 Gson是谷歌发布的一个json解析框架 2、如何获取     github:https://github.com/google/gson     android studio使用 compile 'com.
1689 0
|
2月前
|
安全 数据库 Android开发
在Android开发中实现两个Intent跳转及数据交换的方法
总结上述内容,在Android开发中,Intent不仅是活动跳转的桥梁,也是两个活动之间进行数据交换的媒介。运用Intent传递数据时需注意数据类型、传输大小限制以及安全性问题的处理,以确保应用的健壯性和安全性。
132 11
|
6月前
|
JavaScript Linux 网络安全
Termux安卓终端美化与开发实战:从下载到插件优化,小白也能玩转Linux
Termux是一款安卓平台上的开源终端模拟器,支持apt包管理、SSH连接及Python/Node.js/C++开发环境搭建,被誉为“手机上的Linux系统”。其特点包括零ROOT权限、跨平台开发和强大扩展性。本文详细介绍其安装准备、基础与高级环境配置、必备插件推荐、常见问题解决方法以及延伸学习资源,帮助用户充分利用Termux进行开发与学习。适用于Android 7+设备,原创内容转载请注明来源。
1166 77

热门文章

最新文章