Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert JsonArray to Hashmap

Tags:

java

json

arrays

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}
]
like image 656
Zoef Avatar asked Nov 08 '15 16:11

Zoef


People also ask

Can we convert JSONArray to JSONObject?

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.

Can we convert JSON to Map in Java?

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.

How do I read JSONArray?

String value = (String) jsonObject. get("key_name"); Just like other element retrieve the json array using the get() method into the JSONArray object.

How do I pass a JSON object to a Map?

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.


1 Answers

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);
}
like image 65
Zoef Avatar answered Oct 10 '22 10:10

Zoef