Harshal Kalavadiya
Harshal Kalavadiya

Reputation: 2436

Generate JSONObject dynamically in android

I want to generate the following form

{
"dt": {
    "DocumentElement": [

            {
                "CompanyID": "8",
                "Question": "Who I M?",
                "Answer": "dfsfdsfd"

        },
        {

                "CompanyID": "8",
                "Question": "Who I M?",
                "Answer": "Chintan"

        }
    ]
  }
}

I have one arraylist which is dynamically filled with data and i also want the form in terms of dynamic. Here is my code:

JSONObject DocumentElementobj = new JSONObject();
        JSONArray req = new JSONArray();

        JSONObject reqObj = new JSONObject();
        try {
            for (int i = 0; i < OnLineApplication.mParserResults.size(); i++) {


                reqObj.put("CompanyID", "8");
                reqObj.put("Question",OnLineApplication.mParserResults.get(i).getQuestion());
                reqObj.put("Answer",OnLineApplication.mParserResults.get(i).getAnswer());

            }


            DocumentElementobj.put( "DocumentElement", req );
            System.out.println("Final "+DocumentElementobj.toString());
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

It outputs: Final {"DocumentElement":[]}

EDIT

Thanks to all your response. As per you all responce i make code like below

JSONObject DocumentElementobj = new JSONObject();
        JSONArray req = new JSONArray();
        JSONObject reqObjdt = new JSONObject();

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

                JSONObject reqObj = new JSONObject();
                reqObj.put("CompanyID",   OnLineApplication.mParserResults.get(i).getCompanyId());
                reqObj.put("Question",OnLineApplication.mParserResults.get(i).getQuestion());
                reqObj.put("Answer",OnLineApplication.mParserResults.get(i).getAnswer());
                req.put(reqObj);


            }



            DocumentElementobj.put( "DocumentElement", req );
            reqObjdt.put("dt", DocumentElementobj);
            System.out.println("Final "+reqObjdt.toString());
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

I get foramt which i want but in final string i get sequeence like below

{"dt":
  {"DocumentElement":
    [
    {"Answer": "The Claims Representatives have a small role in return to  work.","Question":"Return-to-Work Claim Issues. Please check the statement that best  applies.","CompanyID":"8"},
    {"Answer":"Poor","Question":"How would you describe the level of your general employee’s understanding of the impact of workers’ compensation costs on your organization?","CompanyID":"8"}]}}

it comes Answer first in sequence but i want to CompanyID first so what is issue in that?

Upvotes: 1

Views: 3578

Answers (4)

Amit Gupta
Amit Gupta

Reputation: 8939

There is a very good Google Libray called gson which help you to create Json Object or Parse Json Object with very ease.

You need to add gson.jar file in your project.

For More details go through the below link.

https://sites.google.com/site/gson/gson-user-guide

Edited Answer:-

public class DocumentElement {
    @Expose
    private String CompanyID;
    @Expose
    private String Question;
    @Expose
    private String Answer;

    public DocumentElement(String CompanyID, String Question, String Answer) {
        this.CompanyID = CompanyID;
        this.Question = Question;
        this.Answer = Answer;
    }

    public String getCompanyID() {
        return CompanyID;
    }

    public String getQuestion() {
        return Question;
    }

    public String getAnswer() {
        return Answer;
    }

}

public class Data {
    @Expose
    private ArrayList<DocumentElement> DocumentElement;

    public ArrayList<DocumentElement> getDocumentElement() {
        return DocumentElement;
    }

    public void setDocumentElement(ArrayList<DocumentElement> DocumentElement) {
        this.DocumentElement = DocumentElement;
    }

}


public class ParentData {
    @Expose
    private Data dt;

    public Data getDt() {
        return dt;
    }

    public void setDt(Data dt) {
        this.dt = dt;
    }

}

And used like this to create JsonObject by help of gson.jar

ArrayList<DocumentElement> doc=new ArrayList<DocumentElement>();
        DocumentElement doc1=new DocumentElement("8", "Who I M?", "Amit");
        DocumentElement doc2=new DocumentElement("9", "Who I M?", "Gupta");
        doc.add(doc1);
        doc.add(doc2);
        Data data=new Data();
        data.setDocumentElement(doc);
        ParentData parent=new ParentData();
        parent.setDt(data);
        Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
        String jsonObj = gson.toJson(parent);
        System.out.println("createdJson:---"+jsonObj);

The Result are

{"dt":{"DocumentElement":[{"Answer":"Amit","CompanyID":"8","Question":"Who I M?"},{"Answer":"Gupta","CompanyID":"9","Question":"Who I M?"}]}}

Hope this will help you.

Upvotes: 1

Jeremy D
Jeremy D

Reputation: 4855

You don't add the reqObj to req.

Do req.put(reqObj)

    JSONObject documentElementobj = new JSONObject();
    JSONArray req = new JSONArray();


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

            JSONObject reqObj = new JSONObject();
            reqObj.put("CompanyID", "8");
            reqObj.put("Question",OnLineApplication.mParserResults.get(i).getQuestion());
            reqObj.put("Answer",OnLineApplication.mParserResults.get(i).getAnswer());
            req.put(reqObj);
        }


        documentElementobj.put( "documentElement", req );
        System.out.println("Final "+ documentElementobj.toString());
    } catch (JSONException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

Also, it is better to make your variables begin with a lowercase letter, usually.

One more thing, using a debugger will be effective in this case.

Upvotes: 1

Denny Sharma
Denny Sharma

Reputation: 3035

Use this code to fullfill your answer :

        JSONObject jObj = new JSONObject("Your web Response");

        JSONObject jObj1 = jObj.getJSONObject("dt");

        JSONArray   item = jObj.getJSONArray("DocumentElement");

        for (int i = 0; i < item.length(); i++) 
        {
            jObj_data = (JSONObject) item.get(i);
             reqObj.put("CompanyID", jObj_data.getString("CompanyID"));
             reqObj.put("Question",jObj_data.getString("Question"));
             reqObj.put("Answer",jObj_data.getString("Answer"));
        }

Upvotes: 0

Pankaj Kumar
Pankaj Kumar

Reputation: 83048

You forgot to add JSONObject reqObj into JSONArray req. like req.put(reqObj);.

Modify your code block from for loop like

JSONObject reqObj = new JSONObject(); // Move inside the loop
reqObj.put("CompanyID", "8");
reqObj.put("Question",OnLineApplication.mParserResults.get(i).getQuestion());
reqObj.put("Answer",OnLineApplication.mParserResults.get(i).getAnswer());
req.put(reqObj); // ADDED HERE

Upvotes: 1

Related Questions