在 java 中使用哈希表创建 json 数组
Create json array with hashtable in java
我对如何使用 JSONObject() 或 google 中的 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"}]}
想通了...!
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);
我对如何使用 JSONObject() 或 google 中的 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"}]}
想通了...!
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);