日期:2014-05-16  浏览次数:20329 次

[Android] Json格式解析和文字图片传输

json串拼写 key=关键字 value=值 ?例:登陆串

?

userString = "eche.lau@gmail.com";
password = "111111";
JSONStringer userInfo = new JSONStringer().object()
					.key("email").value(userString)
                                        .key("password").value(password).endObject();

JSONStringer json = new JSONStringer().object().key("request").value(userInfo).endObject();

?拼写完成的格式是:

?

{
? ? request => {
? ? ? ? ? ? ? ? ? ? ? ? ? :email => "eche.lau@gmail.com",
? ? ? ? ? ? ? ? ? ? ? ? ? :password => "111111"
? ? ? ? ? ? ? ? ? ? ? }
}

?

发送json格式请求方法

?

public static JSONObject getJsonRequest(String url, Object json) {

		HttpPost request = new HttpPost(url);
		String retSrc = null;
		JSONObject result = null;
		try {
			StringEntity se = new StringEntity(json.toString(), HTTP.UTF_8);
                        //设置类型 编码
			se.setContentType("application/json;charset=UTF-8");
			se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
					"application/json;charset=UTF-8"));
			request.setEntity(se);
			// 发送请求
			HttpResponse httpResponse = new DefaultHttpClient()
					.execute(request);
			// 得到应答的字符串
			retSrc = EntityUtils.toString(httpResponse.getEntity());
			// 生成 JSON 对象
			result = new JSONObject(retSrc);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;//返回json对象
	}
?

得到返回json对象并且解析

userRequest = getJsonRequest(Const.URL
					+ "/sign_in.json", json);

int status=userRequest.getInt("status");//获取返回状态数字
JSONObject user = userRequest.getJSONObject("user");
int userId = user.getInt("id");//解析int格式
String nickName = user.getString("nickname");//解析string格式

?返回格式是:

?

{
? ???:status => 200,

? ? ?:user =>?{

? ? ? ? ? ? ? ? ? ? ? ? ?:id => 8,
? ? ? ? ? ? ? ? ? ? ? ? ?:nickname => "逐风林羽",
? ? ? ? ? ? ? ? ? ? }

}

还有数据类型:

JSONArray users = data.getJSONArray("users");

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