有时候我们通过提交数据的时候后台接口要求的数据形式中不仅有普通对象,还有数组对象的形式
如下图所示:
中间这样的数组集合该如何上传呢?
解决办法:
先直接上代码:
List<SellGoodsList> jsonObject;
//单据保存
public void OrderSave() {
try {
final MediaType JSON1 = MediaType.parse("application/json; charset=utf-8");
JSONObject json = new JSONObject();
// 构建数组
JSONArray itemsArray = new JSONArray();
for (int i = 0; i < jsonObject.size(); i++) {
SellGoodsList datas = jsonObject.get(i);
JSONObject item = new JSONObject();
item.put("goodsId", datas.getId());
System.out.println("商品ID" + datas.getId());
item.put("goodsUnitsId", datas.getUnitId());
item.put("retailPrice", Double.parseDouble(datas.getRetailPrice()));
item.put("number", Integer.parseInt(datas.getNumber()));
if (datas.isGift()) {
item.put("isGift", 1);
} else {
item.put("isGift", 0);
}
itemsArray.put(item);
}
json.put("handlerName", handlerName);
json.put("organizationId", organizationId);
json.put("organizationName", organizationName);
json.put("type", 3);
json.put("warehouseId", warehouseId);
json.put("goodsList", itemsArray);
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody body = RequestBody.create(JSON1, String.valueOf(json));
Request request = new Request.Builder()
.url(url + "/admin/v2/warehouse/save?TokenID=" + TokenID)
.post(body).build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("vijoz", "e:"+e.toString());
}
@Override
public void onResponse(Call call, Response response) {
try {
Log.i("vijoz", "111");
String json = response.body().string();
JSONObject jsonObject = new JSONObject(json);
final String status = jsonObject.getString("status");
final String message = jsonObject.getString("message");
if (status.equals("1")) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplication(), "提交成功", Toast.LENGTH_SHORT).show();
}
});
}
Log.i("vijoz", "status:"+status);
} catch (JSONException e) {
Log.i("vijoz", e.toString() + "SS");
} catch (IOException e) {
Log.i("vijoz", e.toString() );
throw new RuntimeException(e);
}
}
});
} catch (Exception e) {
Log.i("vijoz", "报错了:" + e.toString());
}
}
分析:
1、构建一个数组
2、根据list大小不断地往构建的数组里面放入值
3、放入数组集合
4、下面就跟普通的一样开始作网络请求即可
// 构建数组
JSONArray itemsArray = new JSONArray();
//根据list大小不断地往构建的数组里面放入值
for (int i = 0; i < jsonObject.size(); i++) {
//获取要放入的数组对象的值
SellGoodsList datas = jsonObject.get(i);
//构建对象,用来放值
JSONObject item = new JSONObject();
item.put("goodsId", datas.getId());
item.put("goodsUnitsId", datas.getUnitId());
item.put("retailPrice", Double.parseDouble(datas.getRetailPrice()));
item.put("number", Integer.parseInt(datas.getNumber()));
//判断isGift是否为true,若为true放入1,若为false放入0
if (datas.isGift()) {
item.put("isGift", 1);
} else {
item.put("isGift", 0);
}
//把对象放入数组中
itemsArray.put(item);
}
//放入数组集合
json.put("goodsList", itemsArray);
//下面就跟普通的一样开始作网络请求即可
OkHttpClient okHttpClient = new OkHttpClient();
········
这样就可以上传数组集合了