如何写一个json来添加列表?

时间:2015-07-01 19:50:22

标签: java json

我需要像这样创建一个json。

{
    "List": [
        {
            "Description": "ABC",
            "Id": "music",
            "Issent": "0"
        },
        {
            "Description": "ABC",
            "Id": "music",
            "Issent": "0"
        }
    ]
}

这是我用来编写json的代码。但是它没有显示我通过数据库获得的所有值。它重复数据库最后一列的数据

JSONObject jo = new JSONObject();
JSONArray ja = new JSONArray();

Map<String, Object> data = new HashMap<String, Object>();

try {
    Statement ac = DBL.getConnection().createStatement();
    ResultSet r5 = ac.executeQuery("Select * from msg");
    while (r5.next()) {
        System.out.println("Value taken from database" + r5.getString("content"));

        data.put("Description", r5.getString("content"));
        data.put("Id", r5.getString("id"));
        data.put("Issent",r5.getString("issent"));

        ja.put(jo);    
    }
    ja.put(data);

    System.out.println(data);

    JSONObject mainObj = new JSONObject();

    ret = mainObj.put("List", ja).toString();
}

2 个答案:

答案 0 :(得分:1)

    JSONObject final = new JSONObject();
    JSONArray ja = new JSONArray();
try {
    Statement ac = DBL.getConnection().createStatement();
    ResultSet r5 = ac.executeQuery("Select * from msg");
   while(r5.next()){
        System.out.println("Value taken from database"+r5.getString("content"));
        JSONObject jo = new JSONObject();
        jo.put("Description", r5.getString("content"));
        jo.put("Id", r5.getString("id"));
        jo.put("Issent",r5.getString("issent"));
        ja.put(jo);
}

   ret= final.put("List", ja).toString();

尝试以上方法。应该工作。

答案 1 :(得分:0)

我建议

 JSONObject jo = new JSONObject();


 JSONArray ja = new JSONArray();

    try {
        Statement ac = DBL.getConnection().createStatement();
        ResultSet r5 = ac.executeQuery("Select * from msg");
        while(r5.next()){

            System.out.println("Value taken from database"+r5.getString("content"));
            JSONObject element = new JSONObject();

            element.put("Description", r5.getString("content"));
            element.put("Id", r5.getString("id"));
            element.put("Issent",r5.getString("issent"));
            ja.put(element);    
       }

       jo.put( "List", ja );
       System.out.println(jo.toString());
       ret= jo.toString();