android实现从服务器端数据库读数据json解析,Android从服务器端接收json数据并解析的代码...

?

一、从服务器端获取json数据,共有两种形式,分别是HttpUrlConnection,和HttpClient(个人喜 ? ? ? ? ? ? ? ? ? ? ? ? 欢HttpUrlConnection)

?

1、HttpUrlConnection的形式,代码如下:

/**

* 从指定的URL中获取数组

* @param urlPath

* @return

* @throws Exception

*/

public static String readParse(String urlPath) throws Exception {

ByteArrayOutputStream outStream = new ByteArrayOutputStream();

byte[] data = new byte[1024];

int len = 0;

URL url = new URL(urlPath);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

InputStream inStream = conn.getInputStream();

while ((len = inStream.read(data)) != -1) {

outStream.write(data, 0, len);

}

inStream.close();

//通过out.Stream.toByteArray获取到写的数据

return new String(outStream.toByteArray());

}

?2、HttpClient的形式,代码如下:

/**

* 访问数据库并返回JSON数据字符串

*

* @param params 向服务器端传的参数

* @param url

* @return

* @throws Exception

*/

public static String doPost(List params, String url)

throws Exception {

String result = null;

// 获取HttpClient对象

HttpClient httpClient = new DefaultHttpClient();

// 新建HttpPost对象

HttpPost httpPost = new HttpPost(url);

if (params != null) {

// 设置字符集

HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);

// 设置参数实体

httpPost.setEntity(entity);

}

/*// 连接超时

httpClient.getParams().setParameter(

CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);

// 请求超时

httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,

3000);*/

// 获取HttpResponse实例

HttpResponse httpResp = httpClient.execute(httpPost);

// 判断是够请求成功

if (httpResp.getStatusLine().getStatusCode() == 200) {

// 获取返回的数据

result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");

} else {

Log.i("HttpPost", "HttpPost方式请求失败");

}

return result;

}

?

二、解析的代码:

/**

* 解析

*

* @throws JSONException

*/

private static ArrayList> Analysis(String jsonStr)throws JSONException {

JSONArray jsonArray = null;

// 初始化list数组对象

ArrayList> list = new ArrayList>();

jsonArray = new JSONArray(jsonStr);

for (int i = 0; i < jsonArray.length(); i++) {

JSONObject jsonObject = jsonArray.getJSONObject(i);

// 初始化map数组对象

HashMap map = new HashMap();

map.put("a", jsonObject.getString("a"));

map.put("b", jsonObject.getString("b"));

list.add(map);

}

return list;

}

?其中, map.put("a", jsonObject.getString("a"));中a代表json数据,json数据就不说了。。。。。

?

这样,从服务器上得到的json数据就成了我们熟悉的集合数据了。。。

上面的代码主要用到了两个类:JSONArray和JSONObject?

原文:http://hejiawangjava.iteye.com/blog/2247829

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值