首页 > 解决方案 > 如何将嵌套的 Json 数组发布到服务器?

问题描述

嗨,我想使用 JsonObject 将这个包含两个整数的 json 数组的 json 数组发布到服务器

"job_experiences": [
        {
            "job_category": [Integer],
            "experience_level": [Integer]
        }
    ]


  JsonArray list = new JsonArray();

            for (int i = 0; i < selectedJobs.size(); i++) {
                list.add(selectedJobs.get(i));
            }
            JsonArray list2 = new JsonArray();

            for (int i = 0; i < selectedJobs.size(); i++) {
                list2.add(selectedJobs.get(i));
            }




            JsonObject postData = new JsonObject();

        postData.add("job_category", list);
        postData.add("experience_level", list2);

标签: androidjsonpost

解决方案


请使用JSONObject代替JsonObjectJSONArray代替JsonArray,尝试以下方法并检查

JSONArray list = new JSONArray();

for (int i = 0; i < selectedJobs.size(); i++) {
  list.put(selectedJobs.get(i));
}

JSONArray list2 = new JSONArray();

for (int i = 0; i < selectedJobs.size(); i++) {
  list2.put(selectedJobs.get(i));
}


JSONObject postData = new JSONObject();


try {
      postData.put("job_category", list);
      postData.put("experience_level", list2);

      JSONArray job_experiences = new JSONArray();
      job_experiences.put(postData);

      JSONObject jsonObject_job_experiences = new JSONObject();
      jsonObject_job_experiences.put("job_experiences", job_experiences);

      Log.e("jsonObject_job_exp", jsonObject_job_experiences.toString());

    } catch (JSONException e) {
        e.printStackTrace();
    }

在日志中你可以看到最终的JSONObject


推荐阅读