Wilhelmo Gutred
Wilhelmo Gutred

Reputation: 23

How to add JSON values to an ArrayList in Java

I have the following JSON file:

{
  "meta" : {
    "stock" : "AWS",
    "date modified" : 90
  },
  "roles" : [ "Member", "Admin" ],
  "name" : "John Doe",
  "admin" : true,
  "email" : "[email protected]"
}

I wanted to both read the values of the keys and add them to an Array List.

try {
    // create object mapper instance
    ObjectMapper mapper = new ObjectMapper();

    // convert JSON file to map
    Map<?, ?> map = mapper.readValue(Paths.get("user.json").toFile(), Map.class);

    ArrayList<String> data = new ArrayList<String>();
    
    // print map entries
    for (Map.Entry<?, ?> entry : map.entrySet()) {
        System.out.println((entry.getClass()) + "  " + entry.getValue());
        data.add((String)entry.getValue()); // trying to add entry values to arraylist
    }
} catch (Exception ex) {
    ex.printStackTrace();
}

I'm able to print out the data type of the value along with the value itself. All the values are part of class java.util.LinkedHashMap$Entry. I'm not able to cast the values to a String to add them to an ArrayList. How should I go about doing this? Thanks

Upvotes: 0

Views: 1569

Answers (2)

dariosicily
dariosicily

Reputation: 4537

From the jackson-databind documentation you can convert your json to a Map<String, Object> map with the following line (you have boolean, list, number and string values in your json) :

Map<String, Object> map = mapper.readValue(json, Map.class);
// it prints {meta={stock=AWS, date modified=90}, roles=[Member, Admin], name=John Doe, admin=true, [email protected]}
System.out.println(map);

If you want to save your map values string representation into an ArrayList data you can iterate over them with a loop :

List<String> data = new ArrayList<>();
for (Object value : map.values()) {
    data.add(value.toString());
}
//it will print [{stock=AWS, date modified=90}, [Member, Admin], John Doe, true, [email protected]]
System.out.println(data);

Upvotes: 1

Huy Nguyen
Huy Nguyen

Reputation: 2061

Your data type of entries will be like:

meta: Map<String:Object>
roles: List<String>
admin: Boolean

So you will get an exception when casting to string for each entry value. You should handle different data type and convert it according to your request:

Object value = entry.getValue();

I highly recommend you write more few functions to check and convert map/list/primitive variables to expected data (String):

boolean isList(Object obj);
boolean isMap(Object obj);
...
public List<String> convertMap(Map<String,Object> map);
...

Upvotes: 1

Related Questions