Nick Bapu
Nick Bapu

Reputation: 463

JSONObject only copy last value of HashMap

    HashMap<String, Integer> map = new HashMap<>();
    map.put("ID", 1);
    map.put("ID", 2);
    map.put("ID", 3);

    JSONObject jsonObject = new JSONObject(map);
    Log.e("JSON", jsonObject.toString());

OutPut:E/JSON: {"ID":3} Its Funny!!!!

I expect to obtain something like

{"ID":1},{"ID":2},{"ID":3}

Upvotes: 1

Views: 107

Answers (2)

Christian Ascone
Christian Ascone

Reputation: 1177

Json and Maps are key-based.

Your object key must be unique, otherwise it will be replaced.

You should use different keys:

HashMap<String, Integer> map = new HashMap<>();
map.put("ID_1", 1);
map.put("ID_2", 2);
map.put("ID_3", 3);

or use array of maps.

Upvotes: 1

Blackbelt
Blackbelt

Reputation: 157447

That's correct. Map#put overrides the value if a key already exits. In your case:

HashMap<String, Integer> map = new HashMap<>();
map.put("ID", 1);
map.put("ID", 2);
map.put("ID", 3);

you are reusing the key "ID". Your map contains only one pair key/value ID/3. From the documentation (HashMap#put)

Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

On the other hand, the same json object can't contain the same key multiple times.

Upvotes: 1

Related Questions