Android从服务器端接收json数据并解析的代码
16lz
2021-01-25
My Git :https://github.com/hejiawang
一、从服务器端获取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<NameValuePair> 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<HashMap<String, Object>> Analysis(String jsonStr)throws JSONException { JSONArray jsonArray = null; // 初始化list数组对象 ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>(); jsonArray = new JSONArray(jsonStr); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); // 初始化map数组对象 HashMap<String, Object> map = new HashMap<String, Object>(); 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
更多相关文章
- “罗永浩抖音首秀”销售数据的可视化大屏是怎么做出来的呢?
- Nginx系列教程(三)| 一文带你读懂Nginx的负载均衡
- 不吹不黑!GitHub 上帮助人们学习编码的 12 个资源,错过血亏...
- Android(安卓)ListView单选CheckBox
- Android调用接口,获取并解析数据(json格式)
- Android(安卓)用HttpClient 以Post方式提交数据并添加http头信息
- Android实现文件选择
- android OpenGL es lession6
- Android中打电话的数据流程分析