0

I'm a little confused on how to construct associative arrays from a hashtable in java with either JSONObject() or the gson library from google.

Any help on this is appreciated!

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

Result:

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

Desired result:

{"submissions":[{"vote1":"2"},{"vote7":"1"},{"vote25":"1"},{"vote6":"1"},{"vote13":"1"},{"vote9":"1"},{"vote11":"1"}]}
1
  • Oh, ok, i've seen the update. Commented Mar 17, 2015 at 14:41

1 Answer 1

2

Figured it out...!

  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);
Sign up to request clarification or add additional context in comments.

1 Comment

Correct, that's a list of objects with one field, didn't read too closely your update.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.