Android- Create JSON Array and JSON Object

Android- create JSON Array and JSON Object

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

Create json array format in android

Here is code:

  try {
JSONObject jsonObject = new JSONObject();
JSONArray array = new JSONArray();
int[] dataArray = {1,2,3,4,5};
for( int i=0;i<dataArray.length;i++) {
JSONObject internalObject = new JSONObject();
internalObject.put("contact_id",dataArray[i]);
array.put(internalObject);

}
jsonObject.put("contact_approve", array);

System.out.print(jsonObject);
Log.v("JsonObject",jsonObject.toString());
} catch (JSONException e) {
e.printStackTrace();
}

Thanks

How to create JSON Array with Loop Data in Android


JSONArray jsa = new JSONArray();
for (int i = 1; i<= 20; i++) {
JSONObject cust = new JSONObject();
cust.put("number",String.valueOf(i));
cust.put("name","customer"+i);
cust.put("url","url"+i);
jsa.put(cust);
}
System.out.println(jsa.toString());

Add JSONArray to JSONObject in android


        JSONObject object = new JSONObject();
try {
// create multiple object
JSONObject obj1 = new JSONObject();
obj1.put("targetId", 1);
obj1.put("celsius", 34.5);
obj1.put("measuredTime", "2021-03-25,11:40:01");
obj1.put("isFirst", true);

// add all created object in array
JSONArray array = new JSONArray();
array.put(obj1);

// add array in main object
object.put("infos" , array);
} catch (JSONException e) {
e.printStackTrace();
}

How to create Json using JsonArray and JsonObject


    JSONObject obj = new JSONObject();
JSONArray req = new JSONArray();

JSONObject reqObj = new JSONObject()
reqObj.put( "ctrlId", "txt1" );
req.put( reqObj );
reqObj = new JSONObject();
reqObj.put( "ctrlId", "txt2" );
req.put( reqObj );

obj.put( "req", req );

The final object is obj



Related Topics



Leave a reply



Submit