0

I have two array List I want to convert items of array list into json objects & then add those json objects into array list.

Json objects & array

     JSONObject jobj_id=new JSONObject();
     JSONObject jobj_ans=new JSONObject();
     JSONArray qhis_jar=new JSONArray();

code for converting arraylist to json

 for(int i=0;i<arr_quesid.size();i++)
     {
         try {

            jobj_id.put("ques_id", arr_quesid.get(i));
            qhis_jar.put(jobj_id);
            jobj_ans.put("ans", arr_ans.get(i));
            qhis_jar.put(jobj_ans);


        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
     }

But I am getting only the last element of arraylist as json objects.

[{"ques_id":"questionId_7"},{"ques_name":"ans_7"},{"ques_id":"questionId_7"},{"ques_name":"ans_7"},{"ques_id":"questionId_7"},{"ques_name":"ans_7"},{"ques_id":"questionId_7"},{"ques_name":"ans_7"},{"ques_id":"questionId_7"},{"ques_name":"ans_7"},{"ques_id":"questionId_7"},{"ques_name":"ans_7"},{"ques_id":"questionId_7"},{"ques_name":"ans_7"}]

Please tell

2 Answers 2

2

You may use new Gson library...

ArrayList<String> list = new ArrayList<String>();
String jsonData = new Gson().toJson(list);
Sign up to request clarification or add additional context in comments.

2 Comments

is it possible without Gson
convert to JSONObject. toJson returns a String
1

Do it as to create JSONArray which contains other JSONObject's:

for(int i=0;i<arr_quesid.size();i++)
     {      

            jobj_id=new JSONObejct(); // 
            jobj_id.put("ques_id", arr_quesid.get(i));
            qhis_jar.put(jobj_id);
            jobj_ans=new JSONObejct();
            jobj_ans.put("ans", arr_ans.get(i));
            qhis_jar.put(jobj_ans);
     }

because currently you are overriding values jobj_id and jobj_ans with next value that's why qhis_jar JSONArray contain only last values

2 Comments

How can give name to the Json array??
@TechGuy: no possible to give name to JSONArray. you can give name to JSONArray by adding JSONArray to JSONObject like JSONObject.put("array_name",qhis_jar);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.