[android] Android- create JSON Array and JSON Object

How can I create a JSON with this format in Android: Since the API that I will be passing will parse JsonArray then the object. Or would it be okay if just to pass a json object? Since I will just have to insert 1 transaction per service call.

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

What I know is only the JSONObject. Like this one.

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

Any ideas. Thanks

This question is related to android json arrays

The answer is


Use the following code:

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

            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.

Have been struggling with this till I found out the answer:

  1. Use GSON library:

    Gson gson = Gson();
    String str_json = gson.tojson(jsonArray);`
    
  2. Pass the json array. This will be auto stringfied. This option worked perfectly for me.


It's too late to answer, sorry about it, for creating the below body:

{
    "username": "?Rajab",
    "email": "[email protected]",
    "phone": "+93767626554",
    "password": "123asd",
    "carType": "600fdcc646bc6409ae97e2ab",
    "fcmToken":"lljlkdsajfljasldfj;lsa",
    "profilePhoto": "https://st.depositphotos.com/2101611/3925/v/600/depositphotos_39258143-stock-illustration-businessman-avatar-profile-picture.jpg",
    "documents": {
        "DL": [
            {
                "_id": "5fccb687c5b4260011810125",
                "uriPath": "https://webfume-onionai.s3.amazonaws.com/guest/public/document/326634-beats_by_dre-wallpaper-1366x768.jpg"
            }
        ],
        "Registration": [
            {
                "_id": "5fccb687c5b4260011810125",
                "uriPath": "https://webfume-onionai.s3.amazonaws.com/guest/public/document/326634-beats_by_dre-wallpaper-1366x768.jpg"
            }
        ],
        "Insurance":[
              {
                "_id": "5fccb687c5b4260011810125",
                "uriPath": "https://webfume-onionai.s3.amazonaws.com/guest/public/document/326634-beats_by_dre-wallpaper-1366x768.jpg"
            }
        ],
         "CarInside":[
              {
                "_id": "5fccb687c5b4260011810125",
                "uriPath": "https://webfume-onionai.s3.amazonaws.com/guest/public/document/326634-beats_by_dre-wallpaper-1366x768.jpg"
            }
        ],
         "CarOutside":[
              {
                "_id": "5fccb687c5b4260011810125",
                "uriPath": "https://webfume-onionai.s3.amazonaws.com/guest/public/document/326634-beats_by_dre-wallpaper-1366x768.jpg"
            }
        ]
    }
}

You can create dynamically like the below code:

JSONObject jsonBody = new JSONObject();
try {
    jsonBody.put("username", userName);
    jsonBody.put("email", email);
    jsonBody.put("phone", contactNumber);
    jsonBody.put("password", password);
    jsonBody.put("carType", carType);
    jsonBody.put("fcmToken", "lljlkdsajfljasldfj;lsa");
    jsonBody.put("profilePhoto", "https://st.depositphotos.com/2101611/3925/v/600/depositphotos_39258143-stock-illustration-businessman-avatar-profile-picture.jpg");

    JSONObject document = new JSONObject();

    try {
        document.put("DL", createDocument("5fccb687c5b4260011810125", "https://st.depositphotos.com/2101611/3925/v/600/depositphotos_39258143-stock-illustration-businessman-avatar-profile-picture.jpg"));
        document.put("Registration", createDocument("5fccb687c5b4260011810125", "https://st.depositphotos.com/2101611/3925/v/600/depositphotos_39258143-stock-illustration-businessman-avatar-profile-picture.jpg"));
        document.put("Insurance", createDocument("5fccb687c5b4260011810125", "https://st.depositphotos.com/2101611/3925/v/600/depositphotos_39258143-stock-illustration-businessman-avatar-profile-picture.jpg"));
        document.put("CarInside", createDocument("5fccb687c5b4260011810125", "https://st.depositphotos.com/2101611/3925/v/600/depositphotos_39258143-stock-illustration-businessman-avatar-profile-picture.jpg"));
        document.put("CarOutside", createDocument("5fccb687c5b4260011810125", "https://st.depositphotos.com/2101611/3925/v/600/depositphotos_39258143-stock-illustration-businessman-avatar-profile-picture.jpg"));
    } catch (JSONException e) {
        e.printStackTrace();
    }

    jsonBody.put("documents", document.toString());

    Log.i("MAHDI", "Hello: Mahdi: Data: " + jsonBody);
} catch (JSONException e) {
    e.printStackTrace();
}

And the createDocument method code:

public JSONArray createDocument(String id, String imageUrl) {

JSONObject dlObject = new JSONObject();
try {
    dlObject.put("_id", id);
    dlObject.put("uriPath", imageUrl);
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
JSONArray dlArray = new JSONArray();
dlArray.put(dlObject);

return dlArray;
}

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

You can create a a method and pass paramters to it and get the json as a response.

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

I hope this will help you.


Here's a simpler (but not so short) version which doesn't require try-catch:

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

JSONObject jsonData = new JSONObject(data);

If you want to add a jsonObject into a field, you can do this way:

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

Unfortunately it needs a try-catch because of the put() method.

IF you want to avoid try-catch again (not very recommended, but it's ok if you can guarantee well formated json strings), you might do this way:

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

You can do the same about JsonArrays and so on.

Cheers.


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

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


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

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?