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}
]
Core Java bootcamp program with Hands on practiceWe can also add a JSONArray to JSONObject. We need to add a few items to an ArrayList first and pass this list to the put() method of JSONArray class and finally add this array to JSONObject using the put() method.
We can easily convert JSON data into a map because the JSON format is essentially a key-value pair grouping and the map also stores data in key-value pairs. Let's understand how we can use both JACKSON and Gson libraries to convert JSON data into a Map.
String value = (String) jsonObject. get("key_name"); Just like other element retrieve the json array using the get() method into the JSONArray object.
We need to use the JSON-lib library for serializing and de-serializing a Map in JSON format. Initially, we can create a POJO class and pass this instance as an argument to the put() method of Map class and finally add this map instance to the accumulateAll() method of JSONObject.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With