Android数据传递中json的生成和解析
2014-05-27 16:47
459 查看
使用Android集成的JSON包完全可以满足需要。
1. 生成Json数据
输出内容:
2. 解析Json数据
1. 生成Json数据
<span style="font-size:18px;"><span style="white-space:pre"> </span>// 基本map对象 Map baseMap = new HashMap(); baseMap.put("string", "string"); baseMap.put("int", 2); baseMap.put("boolean", true); // Json数组 JSONArray jsonArray = new JSONArray(); jsonArray.put(new JSONObject(baseMap)); jsonArray.put(new JSONObject(baseMap)); jsonArray.put(new JSONObject(baseMap)); // 创建Json格式数据 Map map = new HashMap(); map.put("string", "string"); <span style="white-space:pre"> </span>// 字符串值 map.put("int", 2.5); // 数字 map.put("boolean", true); // 布尔值 map.put("null", null); // null map.put("object", new JSONObject(baseMap)); // Json对象 map.put("array2", jsonArray); <span style="white-space:pre"> </span>// Json数组 // 输出Json JSONObject json = new JSONObject(map); Log.i(TAG, ""+json);</span>
输出内容:
<span style="font-size:18px;">{ "boolean": true, "object": { "int": 2, "boolean": true, "string": "string" }, "int": 2, "null": null, "string": "string", "array": [ { "int": 2, "boolean": true, "string": "string" }, { "int": 2, "boolean": true, "string": "string" }, { "int": 2, "boolean": true, "string": "string" } ] }</span>
2. 解析Json数据
<span style="white-space:pre"> </span>// 原始Json字符串 String jsonString = json.toString(); JSONObject baseJson; try { baseJson = new JSONObject(jsonString); boolean bJson = baseJson.optBoolean("boolean");// 解析布尔类型 int iJson = baseJson.optInt("int");// 解析整型 String sJson = baseJson.optString("string");// 解析字符串 JSONArray jArray = baseJson.optJSONArray("array");// 解析Json数组 Log.i(TAG, "boolean:"+bJson+" int:"+iJson+" string:"+sJson+" array.size:"+jArray.length()); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); }输出:
boolean:true int:2 string:string array.size:3
相关文章推荐
- 【Android开发经验】Json数据格式介绍、使用Android自带类库完成Json生成与解析
- Json数据格式介绍、使用Android自带类库完成Json生成与解析
- Android配置文件分享和JSON数据生成与解析
- Android Gson生成、解析json数据
- Android开发之JSON数据解析和生成
- Android - 获取网络数据,Bitmap,ANR,主线程模型,消息机制,UserAgent,乱码问题,xml生成与解析,JSON解析,MVC,SmartImageView
- Android解析JSON方式(一)服务器端生成JSON数据
- 【Android网络开发の4】解析和生成JSON数据
- json数据解析与生成 android
- 【Android网络开发の4】解析和生成JSON数据
- Android中Json数据的生成与解析
- Json数据格式介绍、使用Android自带类库完成Json生成与解析
- Android与服务器间数据传递及JSON解析
- Json数据格式介绍、使用Android自带类库完成Json生成与解析
- Android开发中使用fastJSON将json格式的数据快速解析生成实体类并附上实体类生成器
- 【Android开发经验】Json数据格式介绍、使用Android自带类库完成Json生成与解析
- Android解析JSON方式 服务器端生成JSON数据--很好的例子
- android 生成json 数据 和解析json数据
- Android解析JSON方式 服务器端生成JSON数据
- 【Android网络开发の4】解析和生成JSON数据