0

I have an ArrayList that contains values as follows

"One"
"Two"
"Three" etc.

I am trying to generate an JSON Object / Array out of this. My code is below:

peopleNames = personAdapter.getArrayListNames();
peoplePhones= personAdapter.getArrayListPhones();

JSONNames = new JSONObject();
JSONPhones =  new JSONObject();

for (int i = 0; i < peopleNames.size(); i++){
    try {
        System.out.println(peopleNames.get(i));
        JSONNames.put("Name",peopleNames.get(i));
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

for (int i = 0; i < peoplePhones.size(); i++){
    try {
        JSONPhones.put("Phone",peoplePhones.get(i));
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

jsonArrayNames = new JSONArray();
System.out.println(jsonArrayNames.toString());

However my output is just:

[{"Name":"One"}]
Rohit5k2
  • 17,948
  • 8
  • 45
  • 57

1 Answers1

1

Why don't you merge the data ? I think, from your adapter, you're able to get people directly, right ? If so, I propose you the following :

people = personAdapter.getPersons();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < people.size(); i++) {
    JSONObject object = new JSONObject();
    object.put("Name", people.name());
    object.put("Phone", people.phone());
    jsonArray.put(object);
}

The resulted JSON will be :

[
  {"Name":"One",
   "Phone": "OnePhone"},
  {"Name":"Two",
   "Phone": "TwoPhone"},
]
Bruno
  • 3,872
  • 4
  • 20
  • 37