您的位置:首页 > 移动开发 > Android开发

Android数据传递中json的生成和解析

2014-05-27 16:47 459 查看
使用Android集成的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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: