10

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
  • 373
  • 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

3 Answers3

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);
}
Alex Karshin
  • 12,300
  • 14
  • 50
  • 60
Zoef
  • 373
  • 2
  • 6
  • 18
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
  • 26,923
  • 21
  • 73
  • 125
Catalin Ciolocoiu
  • 542
  • 1
  • 6
  • 14
-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
  • 401
  • 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