Http获取Json数据,并用Gson解析

对于http访问服务器获取json数据,每个项目中都需要用到的,json解析,个人觉得简单的用jsonobject就可以了,但是遇到接口多的项目,数据量比较大用gson比较方便,减去你很大的负担。

为自己写博客,也是一个好习惯(好记性不如乱笔头)


下载gson-xx.jar   导入libs包


首先http get,post访问服务器获取json数据

public static String httpGet(String url) {
		HttpGet httpGet = new HttpGet(url); // 创建一个GET方式的HttpRequest对象
		HttpClient httpClient = new DefaultHttpClient(); // 创建一个默认的HTTP客户端
		try {
			HttpResponse httpResponse = httpClient.execute(httpGet); // 执行GET方式的HTTP请求
			int reponseCode = httpResponse.getStatusLine().getStatusCode(); // 获得服务器的响应码
			if (reponseCode == HttpStatus.SC_OK) {
				String strResult = EntityUtils.toString(httpResponse
						.getEntity());
				return strResult;
			} else {
				Log.e("httpGet", "GET请求失败!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
public static String httpPost(String url) throws Exception {
		// 第1步:创建HttpPost对象
		HttpPost httpPost = new HttpPost(url);
		// 设置HTTP POST请求参数必须用NameValuePair对象
		/*
		 * Post运作传送变量必须用NameValuePair[]数组储存
		 */
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		NameValuePair paramContent = new BasicNameValuePair(
				"combatBo.username", "admin");
		params.add(paramContent);
		// 设置HTTP POST请求参数
		httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
		// 第2步:使用execute方法发送HTTP POST请求,并返回HttpResponse对象
		HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);
		if (httpResponse.getStatusLine().getStatusCode() == 200) {
			// 第3步:使用getEntity方法获得返回结果
			String result = EntityUtils.toString(httpResponse.getEntity());
			return result;
		} else {
			Log.e("httpPost", "Post请求失败!");
		}
		return null;
	}

第二步,解析Json数据

JsonUtil.java工具类

package com.weihb.httpclient;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class JsonUtil {
	/**
	 * 将Json解析成类对象
	 */
	public static <T> T getPerson(String jsonString, Class<T> cls) {
		T t = null;
		try {
			Gson gson = new Gson();
			t = gson.fromJson(jsonString, cls);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return t;
	}

	public static <T> List<T> getPersons(String jsonString, Class<T> cls) {
		List<T> list = new ArrayList<T>();
		try {
			Gson gson = new Gson();
			list = gson.fromJson(jsonString, new TypeToken<List<T>>() {
			}.getType());

		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	public static List<String> getList(String jsonString) {
		List<String> list = new ArrayList<String>();
		try {
			Gson gson = new Gson();
			list = gson.fromJson(jsonString, new TypeToken<List<String>>() {
			}.getType());
		} catch (Exception e) {
			// TODO: handle exception
		}
		return list;

	}
	public static List<Map<String,Object>> listKeyMap(String jsonString){
		List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
		try {
			Gson gson = new Gson();
			list = gson.fromJson(jsonString, new TypeToken<List<Map<String,Object>>>() {
			}.getType());
		} catch (Exception e) {
			// TODO: handle exception
		}
		return list;
	}
	/**
	 * java对象转json
	 */
	public static String JavaToJson(Object cls) {
		String str = null;
		try {
			Gson gson = new Gson();
			str = gson.toJson(cls);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return str;		
	}
}
第三步,需要数据对应的javabean类

按照json的数据结构,把Bean类造好。注意类的嵌套,还有数据类型,实在不行就全用string,这是蠢办法也是最简单的办法

举个例子:

package com.weihb.httpclient;

import java.io.Serializable;

public class Weather implements Serializable {

	/**
	 * @Fields serialVersionUID :
	 *         {"weatherinfo":{"city":"北京","cityid":"101010100"
	 *         ,"temp1":"22℃","temp2"
	 *         :"9℃","weather":"晴","img1":"d0.gif","img2":"n0.gif","ptime":"11:00"}}
	 */
	private static final long serialVersionUID = -4518932129666918983L;
	private Weatherinfo weatherinfo;

    public Weatherinfo getWeatherinfo() {
        return weatherinfo;
    }

    public void setWeatherinfo(Weatherinfo weatherinfo) {
        this.weatherinfo = weatherinfo;
    }
    public class Weatherinfo implements Serializable{

		/**
		 * @Fields serialVersionUID : 
		 */ 
		private static final long serialVersionUID = 3560815538897448426L;
		private String city;
	    private String cityid;
	    private String temp1;
	    private String temp2;
	    private String weather;
	    private String img1;
	    private String img2;
	    private String ptime;
		public String getCity() {
			return city;
		}
		public void setCity(String city) {
			this.city = city;
		}
		public String getCityid() {
			return cityid;
		}
		public void setCityid(String cityid) {
			this.cityid = cityid;
		}
		public String getTemp1() {
			return temp1;
		}
		public void setTemp1(String temp1) {
			this.temp1 = temp1;
		}
		public String getTemp2() {
			return temp2;
		}
		public void setTemp2(String temp2) {
			this.temp2 = temp2;
		}
		public String getWeather() {
			return weather;
		}
		public void setWeather(String weather) {
			this.weather = weather;
		}
		public String getImg1() {
			return img1;
		}
		public void setImg1(String img1) {
			this.img1 = img1;
		}
		public String getImg2() {
			return img2;
		}
		public void setImg2(String img2) {
			this.img2 = img2;
		}
		public String getPtime() {
			return ptime;
		}
		public void setPtime(String ptime) {
			this.ptime = ptime;
		}
		@Override
		public String toString() {
			return "Weatherinfo [city=" + city + ", cityid=" + cityid
					+ ", temp1=" + temp1 + ", temp2=" + temp2 + ", weather="
					+ weather + ", img1=" + img1 + ", img2=" + img2
					+ ", ptime=" + ptime + "]";
		}
	    
    }
}



接下来的工作就非常简单了,根据jsonutil.java的方法传入bean即可,完成解析和转换成json都无压力。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值