Create Json Array Java Android
[{ 'surveyid': 1 }, {}, {}, {}, {}, {}, {}, { 'question': '1' }, { 'answer': 'john' }, { 'question': '2' }, { 'answer': 'Male' }, {}, { 'question': '3' }, {
Solution 1:
Try this way
JSONObject question1 = newJSONObject();
try {
question1.put("surveyid", "1");
question1.put("question", "1");
question1.put("answer", "john");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject question2 = newJSONObject();
try {
question2.put("surveyid", "5");
question2.put("question", "6");
question2.put("answer", "john2");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray = newJSONArray();
jsonArray.put(question1);
jsonArray.put(question2);
Solution 2:
There are many empty object in your output, it means you have add a empty JSONObject into your JSONArray, I think there is some bad logic in your loop block code, for example if nothing condition meets "if" and "else if" it will produce empty object, it needs a "else" clause.
Solution 3:
To remove empty objects, before adding it to array check its length. if the length is equal to zero then no need to add current object to array. you can do this by using
if(j.length()>0){
myArray.put(j);
}
Solution 4:
Try below code sample
JSONArray jsonArray = newJSONArray();
for (int i = 0; i < 4; i++) {
JSONObjectobject = newJSONObject();
object.put("surveyid", surveyid);
object.put("question", question);
object.put("answer", answer);
jsonArray.put(object);
}
Post a Comment for "Create Json Array Java Android"