Android中处理Json数据
来源:互联网 发布:arm是单片机吗 编辑:程序博客网 时间:2024/06/06 23:40
1.Android中解析Json
JSON数据格式,在Android中被广泛运用于客户端和网络(或者说服务器)通信,非常有必要系统的了解学习。
恰逢本人最近对json做了一个简单的学习,特此总结一下,以飨各位。
为了文章简明清晰,尽量多列点,少废话。
参考文档:http://www.ietf.org/rfc/rfc4627.txt?number=4627
1.JSON解析
(1).解析Object之一:
"url"
"http://www.cnblogs.com/qianxudetianxia"
new
"url"
:
,
:
}
解析方法:
JSONObject(jsonString);
);
);
+name+
+version);
(3).解析Array之一:
"number"
new
"number"
(int i=0; i<numberList.length(); i++){
System.out.println(numberList.getInt(i));
(4).解析Array之二:
"number"
JSONObject(jsonString);
);
int
0
//获取数组中的数组
0
:[{
:
},{
:
}]}
解析方法:
new
"mobile"
(
i=
; i<numberList.length(); i++){
"name"
"url"
"url"
"{"
"}"
1
: {
: 800,
: 600,
:
,
: {
:
<code string"="" style="white-space: pre-wrap; margin: 0px !important; padding: 0px !important; border-radius: 0px !important; border: 0px !important; bottom: auto !important; float: none !important; height: auto !important; left: auto !important; line-height: 2em !important; outline: 0px !important; overflow: visible !important; position: static !important; right: auto !important; top: auto !important; vertical-align: baseline !important; width: auto !important; box-sizing: content-box !important; font-family: 'Courier New', Consolas, 'Bitstream Vera Sans Mono', Courier, monospace !important; color: blue !important; background-image: none !important;">"http://www.example.com/image/481989943""Height"
"Width"
"100"
"IDs"
}
b.Array实例:
"precision"
"zip"
"Latitude"
"Longitude"
"Address"
""
"City"
"SAN FRANCISCO"
"State"
"CA"
"Zip"
"94107"
"Country"
"US"
{
:
,
: 37.371991,
: -122.026020,
:
,
:
,
:
,
:
,
:
}
3.小结
很简单 ,很基础,积水方能成江,累砖才可筑楼。
2.Android利用Gson解析嵌套多层的Json
首先先讲一个比较简单点的例子(最简单的我就不讲啦,网上很多),帮助新手理解Gson的使用方法:
比如我们要解析一个下面这种的Json:
String json = {"a":"100","b":[{"b1":"b_value1","b2":"b_value2"},{"b1":"b_value1","b2":"b_value2"}],"c":{"c1":"c_value1","c2":"c_value2"}}
首先我们需要定义一个序列化的Bean,这里采用内部类的形式,看起来会比较清晰一些:
public class JsonBean {
public String a;
public List<B> b;
public C c;
public static class B {
public String b1;
public String b2;
}
public static class C {
public String c1;
public String c2;
}
}
很多时候大家都是不知道这个Bean是该怎么定义,这里面需要注意几点:
1、内部嵌套的类必须是static的,要不然解析会出错;
2、类里面的属性名必须跟Json字段里面的Key是一模一样的;
3、内部嵌套的用[]括起来的部分是一个List,所以定义为 public List<B> b,而只用{}嵌套的就定义为 public C c,
具体的大家对照Json字符串看看就明白了,不明白的我们可以互相交流,本人也是开发新手!
Gson gson = new Gson();
java.lang.reflect.Type type = new TypeToken<JsonBean>() {}.getType();
JsonBean jsonBean = gson.fromJson(json, type);
然后想拿数据就很简单啦,直接在jsonBean里面取就可以了!
如果需要解析的Json嵌套了很多层,同样可以可以定义一个嵌套很多层内部类的Bean,需要细心的对照Json字段来定义哦。
3.Android从服务器端获取并解析Json
转自:http://www.cnblogs.com/qingblog/archive/2012/10/23/2735026.html
首先客户端从服务器端获取json数据
1、利用HttpUrlConnection
1 /** 2 * 从指定的URL中获取数组 3 * @param urlPath 4 * @return 5 * @throws Exception 6 */ 7 public static String readParse(String urlPath) throws Exception { 8 ByteArrayOutputStream outStream = new ByteArrayOutputStream(); 9 byte[] data = new byte[1024]; 10 int len = 0; 11 URL url = new URL(urlPath); 12 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 13 InputStream inStream = conn.getInputStream(); 14 while ((len = inStream.read(data)) != -1) { 15 outStream.write(data, 0, len); 16 } 17 inStream.close(); 18 return new String(outStream.toByteArray());//通过out.Stream.toByteArray获取到写的数据 19 }
2、利用HttpClient
1 /** 2 * 访问数据库并返回JSON数据字符串 3 * 4 * @param params 向服务器端传的参数 5 * @param url 6 * @return 7 * @throws Exception 8 */ 9 public static String doPost(List<NameValuePair> params, String url)10 throws Exception {11 String result = null;12 // 获取HttpClient对象13 HttpClient httpClient = new DefaultHttpClient();14 // 新建HttpPost对象15 HttpPost httpPost = new HttpPost(url);16 if (params != null) {17 // 设置字符集18 HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);19 // 设置参数实体20 httpPost.setEntity(entity);21 }22 23 /*// 连接超时24 httpClient.getParams().setParameter(25 CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);26 // 请求超时27 httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,28 3000);*/29 // 获取HttpResponse实例30 HttpResponse httpResp = httpClient.execute(httpPost);31 // 判断是够请求成功32 if (httpResp.getStatusLine().getStatusCode() == 200) {33 // 获取返回的数据34 result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");35 } else {36 Log.i("HttpPost", "HttpPost方式请求失败");37 }38 39 return result;40 }
其次Json数据解析:
json数据:[{"id":"67","biaoTi":"G","logo":"http://www.nuoter.com/wtserver/resources/upload/13508741845270.png","logoLunbo":"http://www.nuoter.com/wtserver/resources/upload/13509015004480.jpg","yuanJia":"0","xianJia":"0"},{"id":"64","biaoTi":"444","logo":"http://www.nuoter.com/wtserver/resources/upload/13508741704400.png","logoLunbo":"http://172.16.1.75:8080/wtserver/resources/upload/13508741738500.png","yuanJia":"0","xianJia":"0"},{"id":"62","biaoTi":"jhadasd","logo":"http://www.nuoter.com/wtserver/resources/upload/13508741500450.png","logoLunbo":"http://172.16.1.75:8080/wtserver/resources/upload/13508741557450.png","yuanJia":"1","xianJia":"0"}]
1 /** 2 * 解析 3 * 4 * @throws JSONException 5 */ 6 private static ArrayList<HashMap<String, Object>> Analysis(String jsonStr) 7 throws JSONException { 8 /******************* 解析 ***********************/ 9 JSONArray jsonArray = null;10 // 初始化list数组对象11 ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();12 jsonArray = new JSONArray(jsonStr);13 for (int i = 0; i < jsonArray.length(); i++) {14 JSONObject jsonObject = jsonArray.getJSONObject(i);15 // 初始化map数组对象16 HashMap<String, Object> map = new HashMap<String, Object>();17 map.put("logo", jsonObject.getString("logo"));18 map.put("logoLunbo", jsonObject.getString("logoLunbo"));19 map.put("biaoTi", jsonObject.getString("biaoTi"));20 map.put("yuanJia", jsonObject.getString("yuanJia"));21 map.put("xianJia", jsonObject.getString("xianJia"));22 map.put("id", jsonObject.getInt("id"));23 list.add(map);24 }25 return list;26 }
最后数据适配:
1、TextView
1 /** 2 * readParse(String)从服务器端获取数据 3 * Analysis(String)解析json数据 4 */ 5 private void resultJson() { 6 try { 7 allData = Analysis(readParse(url)); 8 Iterator<HashMap<String, Object>> it = allData.iterator(); 9 while (it.hasNext()) {10 Map<String, Object> ma = it.next();11 if ((Integer) ma.get("id") == id) {12 biaoTi.setText((String) ma.get("biaoTi"));13 yuanJia.setText((String) ma.get("yuanJia"));14 xianJia.setText((String) ma.get("xianJia"));15 }16 }17 } catch (JSONException e) {18 e.printStackTrace();19 } catch (Exception e) {20 e.printStackTrace();21 }22 }
2、ListView:
1 /** 2 * ListView 数据适配 3 */ 4 private void product_data(){ 5 List<HashMap<String, Object>> lists = null; 6 try { 7 lists = Analysis(readParse(url));//解析出json数据 8 } catch (Exception e) { 9 // TODO Auto-generated catch block10 e.printStackTrace();11 }12 List<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();13 for(HashMap<String, Object> news : lists){14 HashMap<String, Object> item = new HashMap<String, Object>();15 item.put("chuXingTianShu", news.get("chuXingTianShu"));16 item.put("biaoTi", news.get("biaoTi"));17 item.put("yuanJia", news.get("yuanJia"));18 item.put("xianJia", news.get("xianJia"));19 item.put("id", news.get("id"));20 21 try {22 bitmap = ImageService.getImage(news.get("logo").toString());//图片从服务器上获取23 } catch (Exception e) {24 // TODO Auto-generated catch block25 e.printStackTrace();26 }27 if(bitmap==null){28 Log.i("bitmap", ""+bitmap);29 Toast.makeText(TravelLine.this, "图片加载错误", Toast.LENGTH_SHORT)30 .show(); // 显示图片编号31 }32 item.put("logo",bitmap);33 data.add(item);34 }35 listItemAdapter = new MySimpleAdapter1(TravelLine.this,data,R.layout.a_travelline_item,36 // 动态数组与ImageItem对应的子项37 new String[] { "logo", "biaoTi",38 "xianJia", "yuanJia", "chuXingTianShu"},39 // ImageItem的XML文件里面的一个ImageView,两个TextView ID40 new int[] { R.id.trl_ItemImage, R.id.trl_ItemTitle,41 R.id.trl_ItemContent, R.id.trl_ItemMoney,42 R.id.trl_Itemtoday});43 listview.setAdapter(listItemAdapter);44 //添加点击 45 listview.setOnItemClickListener(new OnItemClickListener() { 46 public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, 47 long arg3) { 48 login_publicchannel_trl_sub(arg2);49 } 50 });51 }
对于有图片的要重写适配器
1 package com.nuoter.adapterUntil; 2 3 4 import java.util.HashMap; 5 import java.util.List; 6 7 8 import android.content.Context; 9 import android.graphics.Bitmap;10 import android.graphics.BitmapFactory;11 import android.graphics.Paint;12 import android.net.Uri;13 import android.view.LayoutInflater;14 import android.view.View;15 import android.view.ViewGroup;16 import android.widget.BaseAdapter;17 import android.widget.ImageView;18 import android.widget.LinearLayout;19 import android.widget.TextView;20 21 22 public class MySimpleAdapter1 extends BaseAdapter { 23 private LayoutInflater mInflater; 24 private List<HashMap<String, Object>> list; 25 private int layoutID; 26 private String flag[]; 27 private int ItemIDs[]; 28 public MySimpleAdapter1(Context context, List<HashMap<String, Object>> list, 29 int layoutID, String flag[], int ItemIDs[]) { 30 this.mInflater = LayoutInflater.from(context); 31 this.list = list; 32 this.layoutID = layoutID; 33 this.flag = flag; 34 this.ItemIDs = ItemIDs; 35 } 36 @Override 37 public int getCount() { 38 // TODO Auto-generated method stub 39 return list.size(); 40 } 41 @Override 42 public Object getItem(int arg0) { 43 // TODO Auto-generated method stub 44 return 0; 45 } 46 @Override 47 public long getItemId(int arg0) { 48 // TODO Auto-generated method stub 49 return 0; 50 } 51 @Override 52 public View getView(int position, View convertView, ViewGroup parent) { 53 convertView = mInflater.inflate(layoutID, null); 54 // convertView = mInflater.inflate(layoutID, null); 55 for (int i = 0; i < flag.length; i++) {//备注1 56 if (convertView.findViewById(ItemIDs[i]) instanceof ImageView) { 57 ImageView imgView = (ImageView) convertView.findViewById(ItemIDs[i]); 58 imgView.setImageBitmap((Bitmap) list.get(position).get(flag[i]));///////////关键是这句!!!!!!!!!!!!!!!59 60 }else if (convertView.findViewById(ItemIDs[i]) instanceof TextView) { 61 TextView tv = (TextView) convertView.findViewById(ItemIDs[i]); 62 tv.setText((String) list.get(position).get(flag[i])); 63 }else{64 //...备注2 65 } 66 } 67 //addListener(convertView); 68 return convertView; 69 } 70 71 /* public void addListener(final View convertView) {72 73 ImageView imgView = (ImageView)convertView.findViewById(R.id.lxs_item_image);74 75 76 77 } */78 79 }
对于图片的获取,json解析出来的是字符串url:"logoLunbo":http://www.nuoter.com/wtserver/resources/upload/13509015004480.jpg 从url获取 图片
ImageService工具类
1 package com.nuoter.adapterUntil; 2 3 import java.io.ByteArrayOutputStream; 4 import java.io.InputStream; 5 import java.net.HttpURLConnection; 6 import java.net.URL; 7 8 import android.graphics.Bitmap; 9 import android.graphics.BitmapFactory;10 11 12 public class ImageService {13 14 /**15 * 获取网络图片的数据16 * @param path 网络图片路径17 * @return18 */19 public static Bitmap getImage(String path) throws Exception{20 21 /*URL url = new URL(imageUrl); 22 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 23 InputStream is = conn.getInputStream(); 24 mBitmap = BitmapFactory.decodeStream(is);*/25 Bitmap bitmap= null;26 URL url = new URL(path);27 HttpURLConnection conn = (HttpURLConnection) url.openConnection();//基于HTTP协议连接对象28 conn.setConnectTimeout(5000);29 conn.setRequestMethod("GET");30 if(conn.getResponseCode() == 200){31 InputStream inStream = conn.getInputStream();32 bitmap = BitmapFactory.decodeStream(inStream);33 }34 return bitmap;35 }36 37 /**38 * 读取流中的数据 从url获取json数据39 * @param inStream40 * @return41 * @throws Exception42 */43 public static byte[] read(InputStream inStream) throws Exception{44 ByteArrayOutputStream outStream = new ByteArrayOutputStream();45 byte[] buffer = new byte[1024];46 int len = 0;47 while( (len = inStream.read(buffer)) != -1){48 outStream.write(buffer, 0, len);49 }50 inStream.close();51 return outStream.toByteArray();52 }53 54 55 }
上面也将从url处获取网络数据写在了工具类ImageService中方面调用,因为都是一样的。
当然也可以在Activity类中写一个获取服务器图片的函数(当用处不多时)
1 /* 2 3 * 从服务器取图片 4 * 参数:String类型 5 * 返回:Bitmap类型 6 7 */ 8 9 public static Bitmap getHttpBitmap(String urlpath) {10 Bitmap bitmap = null;11 try {12 //生成一个URL对象13 URL url = new URL(urlpath);14 //打开连接15 HttpURLConnection conn = (HttpURLConnection)url.openConnection();16 // conn.setConnectTimeout(6*1000);17 // conn.setDoInput(true);18 conn.connect();19 //得到数据流20 InputStream inputstream = conn.getInputStream();21 bitmap = BitmapFactory.decodeStream(inputstream);22 //关闭输入流23 inputstream.close();24 //关闭连接25 conn.disconnect();26 } catch (Exception e) {27 Log.i("MyTag", "error:"+e.toString());28 }29 return bitmap;30 }
调用:
1 public ImageView pic; 2 ..... 3 ..... 4 allData=Analysis(readParse(url)); 5 Iterator<HashMap<String, Object>> it=allData.iterator(); 6 while(it.hasNext()){ 7 Map<String, Object> ma=it.next(); 8 if((Integer)ma.get("id")==id) 9 {10 logo=(String) ma.get("logo");11 bigpic=getHttpBitmap(logo);12 }13 }14 pic.setImageBitmap(bigpic);
另附 下载数据很慢时建立子线程并传参:
1 new Thread() { 2 @Override 3 public void run() { 4 // 参数列表 5 List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 6 nameValuePairs.add(new BasicNameValuePair("currPage", Integer 7 .toString(1))); 8 nameValuePairs.add(new BasicNameValuePair("pageSize", Integer 9 .toString(5)));10 try {11 String result = doPost(nameValuePairs, POST_URL); 12 Message msg = handler.obtainMessage(1, 1, 1, result);13 handler.sendMessage(msg); // 发送消息14 } catch (Exception e) {15 // TODO Auto-generated catch block16 e.printStackTrace();17 }18 }19 }.start();20 21 // 定义Handler对象22 handler = new Handler() {23 public void handleMessage(Message msg) {24 switch (msg.what) {25 case 1:{26 // 处理UI27 StringBuffer strbuf = new StringBuffer();28 List<HashMap<String, Object>> lists = null;29 try {30 lists = MainActivity.this31 .parseJson(msg.obj.toString());32 } catch (Exception e) {33 // TODO Auto-generated catch block34 e.printStackTrace();35 }36 List<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();37 for(HashMap<String, Object> news : lists){38 HashMap<String, Object> item = new HashMap<String, Object>();39 item.put("id", news.get("id"));40 item.put("ItemText0", news.get("name"));41 42 try {43 bitmap = ImageService.getImage(news.get("logo").toString());44 } catch (Exception e) {45 // TODO Auto-generated catch block46 e.printStackTrace();47 }48 if(bitmap==null){49 Log.i("bitmap", ""+bitmap);50 Toast.makeText(MainActivity.this, "图片加载错误", Toast.LENGTH_SHORT)51 .show(); // 显示图片编号52 }53 item.put("ItemImage",bitmap);54 data.add(item);55 }56 57 //生成适配器的ImageItem <====> 动态数组的元素,两者一一对应58 MySimpleAdapter saImageItems = new MySimpleAdapter(MainActivity.this, data, 59 R.layout.d_travelagence_item, 60 new String[] {"ItemImage", "ItemText0", "ItemText1"}, 61 new int[] {R.id.lxs_item_image, R.id.lxs_item_text0, R.id.lxs_item_text1});62 //添加并且显示63 gridview.setAdapter(saImageItems);64 }65 break;66 default:67 break;68 }69 70 71 }72 };
- Android中处理Json数据
- android中json数据的处理
- Android处理错误json数据
- JavaScript 中处理 JSON 数据
- Unity中处理json数据
- SpringMVC中处理json数据
- Hive中处理json数据
- scala中处理json数据
- Android中JSON数据解析
- Android中解析Json数据
- android中获取json数据
- Android中解析Json数据
- Android中JSON数据使用
- Android用GSon处理Json数据
- Android用GSon处理Json数据
- Android用GSon处理Json数据
- Android用GSon处理Json数据
- Android用GSon处理Json数据
- Ubuntu下安装nasm
- " man stdio "
- Android广播接收器注册问题:Caused by: java.lang.IllegalArgumentException: Receiver not registered
- Unity3d中默认函数调用顺序(MonoBehaviour)
- UVA - 227 Puzzle
- Android中处理Json数据
- 画图解释 SQL join 语句
- Java多线程总结
- 并查集及其在最小生成树中的应用
- apache 虚拟主机和 rewrite 配置及 rewrite规则解释
- IOS,objective_C中用@interface和 @property 方式声明变量的区别
- 面试 如何面试程序员
- Android数据缓存
- 2014年好书排名