11

I've been able to get a jsonarray from a json string, but don't know how to put it in a Hashmap with a String that shows the type of cargo and an Integer showing the amount.

The string:

"cargo":[   
    {"type":"Coals","amount":75309},        
    {"type":"Chemicals","amount":54454},        
    {"type":"Food","amount":31659},     
    {"type":"Oil","amount":18378}
]
Zoef
  • 393
  • 2
  • 6
  • 18
  • possible this link can help http://stackoverflow.com/questions/4307118/jsonarray-to-hashmap – Shriram Nov 08 '15 at 16:05
  • no sorry, already tried that one, some methods don't seem to work with that example – Zoef Nov 08 '15 at 16:17
  • what did you try and what was the result ? – BrunoLevy Nov 08 '15 at 16:45
  • I tried the code from the link you gave me. But "JSONObject" and "optJSONObject" couldn't be resolved, maybe because I use javax.json libraries and that guy uses another library? – Zoef Nov 10 '15 at 09:53

4 Answers4

8

This fixed it for me:

JsonArray jsoncargo = jsonObject.getJsonArray("cargo");

Map<String, Integer> cargo = new HashMap<>();
for (int i = 0; i < jsoncargo.size(); i++) {            
    String type = jsoncargo.getJsonObject(i).getString("type");
    Integer amount = jsoncargo.getJsonObject(i).getInt("amount");
    cargo.put(type, amount);
}
Kevin Kopf
  • 13,327
  • 14
  • 49
  • 66
Zoef
  • 393
  • 2
  • 6
  • 18
  • Error @getJsonObject method – Ajay Takur Apr 17 '19 at 10:09
  • should be length() instead of size()? – DrAchernar Feb 24 '22 at 07:38
  • How is this going to work? The last item of `type` and `amount` will win, and I don't see how the list is going to be created on the map. I think it should be defined as `Map cargList = new HasMap<>()` then generate the array list `myCargoList` from the JSON Array, and add it to the map using `cargo.put("cargoList", myCargoList)`. Please let me know if this is the correct understanding. – tarekahf Sep 16 '22 at 05:37
0

I've been able to solve this using the Google GSON

    Map<String, Integer> cargoMap = new HashMap<>();

    JsonObject jsonObject = new Gson().fromJson(yourJsonString, JsonObject.class);
    JsonArray cargo = jsonObject.getAsJsonArray("cargo");
    cargo.forEach(item ->
    {
        String type = item.getAsJsonObject().get("type").getAsString();
        int amount = item.getAsJsonObject().get("amount").getAsInt();
        if (StringUtils.isNotBlank(type) || amount != 0) {
            cargoMap.put(type, amount);
        }
    });

Where "yourJsonString" is the whole json that contains the cargo json array.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Catalin Ciolocoiu
  • 542
  • 1
  • 6
  • 15
0

If the JSON is

    [
        {
            "key": "customerRefNo",
            "value": "A"
        }
    ]
   

 Map<String, String> map = new HashMap<>();
        params.forEach(e -> map.put(e.get("key").asText(), e.get("value").asText()));
-1

Try creating a new HashMap, and loop through the JSONArray, adding each element to the hashmap.

JSONArray allCargo = jsonObject.getJsonArray("cargo");

HashMap<String, String> hm = new HashMap();

for(Object cargo : allCargo) {
    LinkedHashMap lhm = (LinkedHashMap) cargo;
    hm.put((String)lhm.get("type"), (String)lhm.get("amount"));
}
Satya
  • 429
  • 3
  • 8
  • 1
    While this code may solve the question, [including an explanation](https://meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply. – David Buck Mar 12 '20 at 10:46