使用java中的哈希表创建json数组

时间:2015-03-17 14:30:43

标签: java json gson jsonobject

我对如何使用JSONObject()或谷歌的gson库从java中的哈希表构造关联数组感到困惑。

对此有任何帮助表示赞赏!

    JSONObject message = new JSONObject();
    Map<String,String> responseData = new Hashtable<String, String>();

[...]

    ResultSet results = getApprovalCount.executeQuery();

    while (results.next()) {
        responseData.put("vote" + results.getString("submission_id"), results.getString("counter"));
    }

[...]

    message.put("submissions", responseData);

结果:

{"submissions":{"vote1":"2","vote7":"1","vote25":"1","vote6":"1","vote13":"1","vote9":"1","vote11":"1"}}

期望的结果:

{"submissions":[{"vote1":"2"},{"vote7":"1"},{"vote25":"1"},{"vote6":"1"},{"vote13":"1"},{"vote9":"1"},{"vote11":"1"}]}

1 个答案:

答案 0 :(得分:2)

想出来......!

  JSONObject message = new JSONObject();
  ArrayList<Map<String,String>> responseData = new ArrayList<Map<String,String>>();
  User user = new User(request);

[...]

    while (results.next()) {
        Map<String,String> tmpdata = new Hashtable<String, String>();
        tmpdata.put("vote" + results.getString("submission_id"), results.getString("counter"));
        responseData.add(tmpdata);
    }

[...]

    message.put("submissions", responseData);