返回的response解析:
Bean ret = null;
ret = parseJson(response, OldBackupDetails.class);
//这样写更健壮一些
public static <T> T parseJson(Response response, Class<T> type) {
T t = null;
if ((response != null) && (response.body() != null)) {
try {
String content = null;
try {
content = response.body().string();
} catch (IOException e) {
CloudLogUtil.e(TAG, "parseJson" + e);
}
if (CloudLogUtil.sQeAssert) {
CloudLogUtil.i(TAG, "content " + content);
}
if (!TextUtils.isEmpty(content)) {
try {
Gson gson = new Gson();
t = gson.fromJson(content, type);
} catch (Exception e) {
CloudLogUtil.d(TAG, "parseJson:" + e.getMessage());
}
}
} catch (Exception e) {
CloudLogUtil.e(TAG, "parseJson " + e);
}
response.close();
}
return t;
}
post传参数:
例子:{"consumer":"18200000000","buyer":"18200000000","coupons":[],"products":[{"product_id":"393","numbe":"1"}]}
JSONObject mainbject = new JSONObject();
//products
JSONArray productslist = new JSONArray();
JSONObject productsobj = new JSONObject();
productsobj.put("product_id","393");
productsobj.put("numbe","1");
productslist.put(productsobj);
//coupons
JSONArray list = new JSONArray();
//暂时传值为空就可以,如果不为空而是集合则下面的方式
/*JSONObject str1 = new JSONObject();
JSONObject str2 = new JSONObject();
str1.put("coupon_id","1001");
str2.put("coupon_id","1");
list.put(str1);
list.put(str2);*/
mainbject.put("products",productslist); mainbject.put("coupons",list);
自己手动解析:
{"body" : {"mobile":"13714664734","email":"","icon":"","open_id":"f5994ced6530405ebc07f8fecd1beb12","country_code":"86","user_name":"13714664734","is_update_name":"0"},
"code":"0","msg":"成功"}
{}:是对象--->
sonObject = new JSONObject(response);
jsonBody = jsonObject.optJSONObject("body");
String mobile= jsonBody .optString("mobile");
{
"body": {
"products": [ {
"describe": "无流量限制",
"type": 1, //产品类型(0:虚拟 1:实际)
"
}],
"coupons": [ {
"name": "折扣券", //优惠券名称
"describe": "", //优惠券描述
}],
"amount": 12.11, //订单总金额
"order_num": "12000100", //订单流水号
},
"code": "0",
"msg": "成功"
}
[]:是集合 :
JSONArray jsonArrayProList = jsonBody.optJSONArray("products");
jsonArrayProList 是集合,定义循环,解析多个products.
JSONObject jsonObjectOne = jsonArrayProList.optJSONObject(i);
String describe = jsonObjectOne.optString("describe");