Android 之 数组转JSON

Android 之
数组转JSON
post 多层级 Body 上传服务器

image.png

Android 之 数组转JSON:

        // 账号密码转为Json格式传给后台
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        // 将要传的参数保存进Json对象
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("username", "mobile");
            jsonObject.put("password", "password");
            JSONArray jsonArray = new JSONArray();

            JSONObject tmpObj = null;
            tmpObj = new JSONObject();
            tmpObj.put("name", "张三");
            tmpObj.put("sex", "男");
            tmpObj.put("age", "16");

            jsonArray.put(tmpObj);

            jsonObject.put("personInfos", jsonArray); // 获得JSONObject的String

        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.d("111111 LogonActivity>>", "jsJson ====:" + jsonObject);

Log打印:

image.png

{
    "username": "mobile",
    "password": "password",
    "personInfos": [{
        "name": "张三",
        "sex": "男",
        "age": "16"
    }]
}

image.png

第二种写法:

        // 账号密码转为Json格式传给后台
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        // 将要传的参数保存进Json对象
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", "mobile");
        jsonObject.put("password", "password");

        JSONArray jsonArray = new JSONArray();
        List personList = new ArrayList();  //中已经装载好了数据:
        JSONObject tmpObj = null;
        int count = personList.size();
        for(int i = 0; i < count; i++) {
            tmpObj = new JSONObject();
            tmpObj.put("name", personList.get(i).name);
            tmpObj.put("sex", personList.get(i).sex);
            tmpObj.put("age", personList.get(i).age);
            jsonArray.put(tmpObj);
//            tmpObj = null;
        }
        Log.d("111111 LogonActivity>>", "jsJson ====:" + jsonObject);

。。。

猜你喜欢

转载自blog.csdn.net/jun_tong/article/details/127977982
今日推荐