Android-创建JSON数组和JSON对象


122

如何在Android中以这种格式创建JSON:由于我将传递的API将解析JsonArray,然后解析该对象。还是只传递一个json对象就可以了吗?因为我只需要在每个服务调用中插入1个事务即可。

{
    "student": [
        {
            "id": 1,
            "name": "John Doe",
            "year": "1st",
            "curriculum": "Arts",
            "birthday": 3/3/1995
        },
        {
            "id": 2,
            "name": "Michael West",
            "year": "2nd",
            "curriculum": "Economic",
            "birthday": 4/4/1994
        }
    ]
}

我所知道的只是JSONObject。像这个。

JSONObject obj = new JSONObject();
try {
    obj.put("id", "3");
    obj.put("name", "NAME OF STUDENT");
    obj.put("year", "3rd");
    obj.put("curriculum", "Arts");
    obj.put("birthday", "5/5/1993");
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

有任何想法吗。谢谢



将JSONObject放在JSONArray中以实现发布的格式
。.– sftdev

Answers:


314

使用以下代码:

JSONObject student1 = new JSONObject();
try {
    student1.put("id", "3");
    student1.put("name", "NAME OF STUDENT");
    student1.put("year", "3rd");
    student1.put("curriculum", "Arts");
    student1.put("birthday", "5/5/1993");

} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

JSONObject student2 = new JSONObject();
try {
    student2.put("id", "2");
    student2.put("name", "NAME OF STUDENT2");
    student2.put("year", "4rd");
    student2.put("curriculum", "scicence");
    student2.put("birthday", "5/5/1993");

} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}


JSONArray jsonArray = new JSONArray();

jsonArray.put(student1);
jsonArray.put(student2);

JSONObject studentsObj = new JSONObject();
    studentsObj.put("Students", jsonArray);



String jsonStr = studentsObj.toString();

    System.out.println("jsonString: "+jsonStr);

完美的例子!
阿亚兹·阿里夫

27
public JSONObject makJsonObject(int id[], String name[], String year[],
            String curriculum[], String birthday[], int numberof_students)
            throws JSONException {
        JSONObject obj = null;
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < numberof_students; i++) {
            obj = new JSONObject();
            try {
                obj.put("id", id[i]);
                obj.put("name", name[i]);
                obj.put("year", year[i]);
                obj.put("curriculum", curriculum[i]);
                obj.put("birthday", birthday[i]);

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            jsonArray.put(obj);
        }

        JSONObject finalobject = new JSONObject();
        finalobject.put("student", jsonArray);
        return finalobject;
    }

感谢这种简单的方法。
KishuDroid

5
 JSONObject obj = new JSONObject();
            try {
                obj.put("id", "3");
                obj.put("name", "NAME OF STUDENT");
                obj.put("year", "3rd");
                obj.put("curriculum", "Arts");
                obj.put("birthday", "5/5/1993");

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
             JSONArray js=new JSONArray(obj.toString());
             JSONObject obj2 = new JSONObject();
             obj2.put("student", js.toString());

我假设'JSONObject obj2 = new JSONObject();中的'obj'; obj.put(“ student”,js.toString());' 是'obj2'吗?
sftdev

4

您可以创建一个方法并将参数传递给该方法,并获取json作为响应。

  private JSONObject jsonResult(String Name,int id, String curriculum) throws JSONException {
        JSONObject json = null;
        json = new JSONObject("{\"" + "Name" + "\":" + "\"" + Name+ "\""
            + "," + "\"" + "Id" + "\":" + id + "," + "\"" + "Curriculum"
            + "\":" + "\"" + curriculum+ "\"" + "}");
        return json;
      }

我希望这能帮到您。


3

这是一个更简单(但不是很短)的版本,不需要try-catch:

Map<String, String> data = new HashMap<>();
data.put("user", "mark@facebook.com");
data.put("pass", "123");

JSONObject jsonData = new JSONObject(data);

如果要将JSONObject添加到字段中,可以采用以下方式:

data.put("socialMedia", (new JSONObject()).put("facebookId", "1174989895893400"));
data.put("socialMedia", (new JSONObject()).put("googleId", "106585039098745627377"));

不幸的是,由于put()方法,它需要尝试捕获。

如果您想避免再次尝试捕获(不建议这样做,但是可以保证格式正确的json字符串也可以),您可以这样做:

data.put("socialMedia", "{ 'facebookId': '1174989895893400' }");

您可以对JsonArrays等执行相同的操作。

干杯。


1

一直在为此苦苦挣扎,直到我找到答案:

  1. 使用GSON库:

    Gson gson = Gson();
    String str_json = gson.tojson(jsonArray);`
  2. 传递json数组。这将被自动字符串化。这个选项对我来说非常合适。


1
JSONObject jsonResult = new JSONObject();
try {
  jsonResult.put("clave", "valor");
  jsonResult.put("username", "iesous");
  jsonResult.put("password", "1234");

} catch (JSONException e) {
  // TODO Auto-generated catch block
 e.printStackTrace();
}

Log.d("DEV","jsonResult->"+jsonResult);

3
您应该添加一些叙述来解释您的答案并改进格式。
rghome '16

0
            Map<String, String> params = new HashMap<String, String>();

            //** Temp array
            List<String[]> tmpArray = new ArrayList<>();
            tmpArray.add(new String[]{"b001","book1"}); 
            tmpArray.add(new String[]{"b002","book2"}); 

            //** Json Array Example
            JSONArray jrrM = new JSONArray();
            for(int i=0; i<tmpArray.size(); i++){
                JSONArray jrr = new JSONArray();
                jrr.put(tmpArray.get(i)[0]);
                jrr.put(tmpArray.get(i)[1]);
                jrrM.put(jrr);
            }

           //Json Object Example
           JSONObject jsonObj = new JSONObject();
            try {
                jsonObj.put("plno","000000001");                   
                jsonObj.put("rows", jrrM);

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


            // Bundles them
            params.put("user", "guest");
            params.put("tb", "book_store");
            params.put("action","save");
            params.put("data", jsonObj.toString());

           // Now you can send them to the server.

0
  public void DataSendReg(String picPath, final String ed2, String ed4, int bty1, String bdatee, String ed1, String cno, String address , String select_item, String select_item1, String height, String weight) {

      final ProgressDialog dialog=new ProgressDialog(SignInAct.this);
      dialog.setMessage("Process....");
      AsyncHttpClient httpClient=new AsyncHttpClient();
      RequestParams params=new RequestParams();
      File pic = new File(picPath);
      try {
          params.put("image",pic);
      } catch (FileNotFoundException e) {
          e.printStackTrace();
      }
      params.put("height",height);
      params.put("weight",weight);
      params.put("pincode",select_item1);
      params.put("area",select_item);
      params.put("address",address);
      params.put("contactno",cno);
      params.put("username",ed1);
      params.put("email",ed2);
      params.put("pass",ed4);
      params.put("bid",bty1);
      params.put("birthdate",bdatee);
      params.put("city","Surat");
      params.put("state","Gujarat");


      httpClient.post(WebAPI.REGAPI,params,new JsonHttpResponseHandler(){
          @Override
          public void onStart() {
              dialog.show();
          }

          @Override
          public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
              try {
                  String done=response.get("msg").toString();
                  if(done.equals("s")) {
                      Toast.makeText(SignInAct.this, "Registration Success Fully", Toast.LENGTH_SHORT).show();
                      DataPrefrenceMaster.SetRing(ed2);
                      startActivity(new Intent(SignInAct.this, LoginAct.class));
                      finish();
                  }
                  else  if(done.equals("ex")) {
                      Toast.makeText(SignInAct.this, "email already exist", Toast.LENGTH_SHORT).show();
                  }else Toast.makeText(SignInAct.this, "Registration failed", Toast.LENGTH_SHORT).show();
              } catch (JSONException e) {
                  Toast.makeText(SignInAct.this, "e :: ="+e.getMessage(), Toast.LENGTH_SHORT).show();
              }
          }

          @Override
          public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
              Toast.makeText(SignInAct.this, "Server not Responce", Toast.LENGTH_SHORT).show();
              Log.d("jkl","error");
          }

          @Override
          public void onFinish() {
                   dialog.dismiss();
        }
    });
}

这将有助于在您的代码中添加一些上下文解释,因为您似乎在回答错误的问题...
Tomerikoo

0
    httpClient.post("your api", params, new JsonHttpResponseHandler() {
        @Override
        public void onStart() {
            dialog.show();
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            try {
                JSONArray jsonArray=response.getJSONArray("data");
                for (int i = 0; i <jsonArray.length() ; i++) {
                    blootypelist1.add(jsonArray.getJSONObject(i).getString("email"));
                }
                ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_activated_1, blootypelist1);

                // Drop down layout style - list view with radio button

                // attaching data adapter to spinner
                listView.setAdapter(dataAdapter);
            } catch (JSONException e) {
                blootypelist1.clear();
                Toast.makeText(context, "No search user avelible", Toast.LENGTH_SHORT).show();
            }
        }

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.