Reputation: 57
try {
jsonObjectt.put("senderId", "XYZ");
jsonObjectt.put("User_Type", usertype);
jsonObjectt.put("Text_message", message);
for(int i=0; i<=selectedUserIdListArray.size(); i++) {
try {
jsonObject.put("Stud_ID", selectedUserIdListArray.get(i));
jsonObject.put("Mobile_No", selectedUserNoListArray.get(i));
jsonArray.put(jsonObject);
}catch (Exception e){
e.printStackTrace();
}
}
jsonObjectt.put("studData",jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
what i expect :
{
"senderId":"XYZ",
"User_Type":"student",
"Text_message":"jgz ",
"studData": [{
"Stud_ID":"100S1000","Mobile_No":"123456789"
},
{
"Stud_ID":"100S1010","Mobile_No":"321654987"
}]
}
what i am getting:
{
"senderId":"XYZ",
"User_Type":"student",
"Text_message":"jgz ",
"studData": [{
"Stud_ID":"100S1000","Mobile_No":"123456789"
},
{
"Stud_ID":"100S1000","Mobile_No":"123456789"
}]
}
Upvotes: 1
Views: 63
Reputation: 26
Instead jsonArray.put can you try with jsonArray.add
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class JSONPractise {
public static void main(String[] args) {
JSONObject jsonObjectt = new JSONObject();
List<Student> selectedUserIdListArray = new ArrayList<>();
selectedUserIdListArray.add(new Student("100S1000", "1234567890"));
selectedUserIdListArray.add(new Student("100S1010", "3216549870"));
JSONArray jsonArray = new JSONArray();
try {
jsonObjectt.put("senderId", "XYZ");
jsonObjectt.put("User_Type", "student");
jsonObjectt.put("Text_message", "xzf");
for(int i=0; i<selectedUserIdListArray.size(); i++) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("Stud_ID", selectedUserIdListArray.get(i).getId());
jsonObject.put("Mobile_No", selectedUserIdListArray.get(i).getPhoneNumber());
jsonArray.add(jsonObject);
}catch (Exception e){
e.printStackTrace();
}
}
jsonObjectt.put("studData",jsonArray);
System.out.println(jsonObjectt);
}catch (Exception e)
{
System.out.println(e);
}
}
}
Output:
{
"senderId":"XYZ",
"studData":[
{
"Mobile_No":"1234567890",
"Stud_ID":"100S1000"
},
{
"Mobile_No":"3216549870",
"Stud_ID":"100S1010"
}
],
"Text_message":"xzf",
"User_Type":"student"
}
Upvotes: 1