How to get an jsonarray from a list of strings

Viewed 1540

I recently did a coding challenge and was really stuck on how to get the values from a list of strings to be a JSONArray.

Let's say given a list of classes, you want the names of the students to be stored in a JSONArray.

First Grade
Tom
Cat
Ed
Crystal

Second Grade
Phoebe
Cindy
Jill
Matt

Third Grade
Crystal
Ben
Harry
Leo

// To access all the lists in the collection
List<String> classes = new ArrayList<String>(jsonInput.keySet());

After that, do I loop through classes to get the names and put them into a JSONArray?

2 Answers

Add below dependency to your code

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.8.5</version>
</dependency>

And add your lists in map and then convert it to JSON String.

Map<String, List<String>> map=new HashMap<>();
map.put("First Grade", list1);
map.put("Second Grade", list2);
map.put("Third Grade", list3);
ObjectMapper mapper = new ObjectMapper();
try {
    String json = mapper.writeValueAsString(map);
    System.out.println(json);
} catch (JsonProcessingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

If you are going from a ArrayList<String> to JSONArray then you can use GSON library

ArrayList<String> listOfStudentNames = new ArrayList<String>;
listOfStudentNames.add("Tom");
listOfStudentNames.add("Cat");
listOfStudentNames.add("Ed");
...
Gson gson = new Gson();
String data = gson.toJson(listOfStudentNames);
JsonArray jsonArray = new JsonParser().parse(data).getAsJsonArray();
Related