Android- buat JSON Array dan JSON Object

122

Bagaimana cara membuat JSON dengan format ini di Android: Karena API yang akan saya lewati akan mengurai JsonArray lalu objeknya. Atau akankah tidak masalah jika hanya memberikan objek json? Karena saya hanya perlu memasukkan 1 transaksi per panggilan layanan.

{
    "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
        }
    ]
}

Yang saya tahu hanyalah JSONObject. Seperti yang ini.

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();
}

Ada ide. Terima kasih

sftdev
sumber
1
tautan referensi
Chintan Khetiya
menempatkan JSONObject dalam JSONArray untuk mencapai format yang diposting ..
sftdev
Lihatlah pengembang
JSONArray.android.com/reference/org/json/JSONArray.html

Jawaban:

314

Gunakan kode berikut:

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);
Suji
sumber
Contoh yang sempurna!
Ayaz Alifov
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;
    }
Jitesh Upadhyay
sumber
Terima kasih untuk metode mudah ini.
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());
Jai Kumar
sumber
saya berasumsi bahwa 'obj' dalam 'JSONObject obj2 = new JSONObject (); obj.put ("mahasiswa", js.toString ()); ' itu 'obj2'?
sftdev
4

Anda dapat membuat metode dan meneruskan parameter ke sana dan mendapatkan json sebagai respons.

  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;
      }

Saya harap ini akan membantu Anda.

Swapnil Kotwal
sumber
3

Berikut adalah versi yang lebih sederhana (tetapi tidak terlalu pendek) yang tidak memerlukan coba-coba:

Map<String, String> data = new HashMap<>();
data.put("user", "[email protected]");
data.put("pass", "123");

JSONObject jsonData = new JSONObject(data);

Jika Anda ingin menambahkan jsonObject ke dalam bidang, Anda dapat melakukannya dengan cara ini:

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

Sayangnya itu perlu mencoba menangkap karena metode put ().

JIKA Anda ingin menghindari coba-tangkap lagi (tidak terlalu disarankan, tetapi tidak masalah jika Anda dapat menjamin string json yang diformat dengan baik), Anda dapat melakukan cara ini:

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

Anda dapat melakukan hal yang sama tentang JsonArays dan seterusnya.

Bersulang.

felippe
sumber
1

Telah berjuang dengan ini sampai saya menemukan jawabannya:

  1. Gunakan pustaka GSON:

    Gson gson = Gson();
    String str_json = gson.tojson(jsonArray);`
  2. Lulus array json. Ini akan otomatis dirangkai. Opsi ini bekerja dengan sempurna untuk saya.

Simon Muthusi
sumber
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);
Jesús Flor Farias
sumber
3
Anda harus menambahkan beberapa narasi untuk menjelaskan jawaban Anda dan meningkatkan pemformatan.
rghome
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.
TobScada
sumber
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();
        }
    });
}
Brijesh D Gondaliya
sumber
Ini akan membantu untuk menambahkan beberapa penjelasan konteks dengan kode Anda karena tampaknya Anda menjawab pertanyaan yang salah ...
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();
            }
        }
Brijesh D Gondaliya
sumber