Im trying to take the values from the ArrayList
and put in to an JSONObject
. I have written the below code but it does only put the last value from arraylist to jsonobject
I am trying to achieve this out put.
{"lstContacts":"array_value"},{"lstContacts":"array_value"},{"lstContacts":"array_value"}
This is my code
ArrayList<String> tokens;
JSONObject contactsObj;
..
...
test.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
for (int i = 0; i < tokens.size(); i++) {
contactsObj.put("ContactToken", tokens.get(i));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String jsonStr = contactsObj.toString();
Log.e("CONTACTS", jsonStr); // adds only last array to json object
}
});
Mohammed NasrullahMohammed Nasrullah
asked Nov 2, 2015 at 15:47
4 Answers 4
Try this:
JSONObject contactsObj = new JSONObject();
JSONArray contactsArray = new JSONArray();
try {
for (int i = 0; i < tokens.size(); i++) {
JSONObject contact = new JSONObject();
contact.put("ContactToken", tokens.get(i));
contactsArray.put(i, contact);
}
contactsObj.put("contacts", contactsArray);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String jsonStr = contactsObj.toString();
Log.e("CONTACTS", jsonStr); // adds only last array to json object
The result jsonStr will look like this:
{
"contacts":[
{
"ContactToken":"someToken"
},
{
"ContactToken":"someToken"
},
{
"ContactToken":"someToken"
},
{
"ContactToken":"someToken"
}
]
}
answered Nov 2, 2015 at 15:58
Sign up to request clarification or add additional context in comments.
1 Comment
Cruncher
You should post what the resulting object would look like.
You are overriding the object because u are using an JsonObject
for an ArrayList
, the solution is to use an JsonArray
contactObj in your case
JSONArray contactsObj;
for (int i = 0; i < tokens.size(); i++) {
contactsObj.put(i, tokens.get(i));
}
Comments
JSONObject contactsObj = new JSONObject();
for (int i = 0; i < tokens.size(); i++) {
contactsObj.put("lstContacts" + String.valueOf(i), tokens.get(i));
}
// done...
answered Nov 2, 2015 at 15:54
1 Comment
Xjasz
A JSONArray is better but he wants a JSONObject
contactsObj.put("ContactTokens", new JSONArray(tokens));
Is probably closest to what you're looking for. You don't even need to loop for this.
This will give you the object
{
"ContactTokens":["token1","token2","token3"...]
}
answered Nov 2, 2015 at 15:55
Comments
lang-java
contactsObj
needs to be aJSONArray