在android中动态生成JSONObject

时间:2013-10-11 06:10:11

标签: android json

我想生成以下表格

{
"dt": {
    "DocumentElement": [

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

        },
        {

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

        }
    ]
  }
}

我有一个动态填充数据的arraylist,我也希望表单是动态的。这是我的代码:

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();
        }

输出:   最终{“DocumentElement”:[]}

修改

感谢您的回复。根据你们所有人的反应,我制作如下代码

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();
        }

我得到了我想要的foramt但是在最后的字符串中我得到了如下所示的序列

{"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"}]}}

它首先按顺序回答,但我首先想要CompanyID,那么问题是什么呢?

4 个答案:

答案 0 :(得分:1)

有一个非常好的Google Libray,名为gson,可以帮助您轻松创建Json Object或Parse Json Object。

您需要在项目中添加gson.jar文件。

详情请参阅以下链接。

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

编辑答案: -

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;
    }

}

并使用这样的方法通过gson.jar

的帮助创建JsonObject
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);

结果

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

希望这会对你有所帮助。

答案 1 :(得分:1)

您忘了将 JSONObject reqObj添加到 JSONArray req中。比如req.put(reqObj);

for loop

修改您的代码块
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

答案 2 :(得分:1)

您不会将reqObj添加到req。

执行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();
    }

此外,最好让变量以小写字母开头,通常是。

还有一件事,在这种情况下使用调试器会很有效。

答案 3 :(得分:0)

使用此代码来完成答案: