Friday, May 14, 2021

How can we convert a JSON array to a list in java

Java-based library and it can be useful to convert Java objects to JSON and JSON to Java Object. A Jackson API is faster than other API, needs less memory area and is good for the large objects. We can convert a JSON array to a list using the ObjectMapper class. It has a useful method readValue() which takes a JSON string and converts it to the object class specified in the second argument.

import java.util.*;

import com.fasterxml.jackson.databind.*;

public class JSONArrayToListTest1 {

   public static void main(String args[]) {

      String jsonStr = "[\"INDIA\", \"AUSTRALIA\", \"ENGLAND\", \"SOUTH AFRICA\", \"WEST INDIES\"]";

      ObjectMapper objectMapper = new ObjectMapper();

      try {

         List<String> countries = objectMapper.readValue(jsonStr, List.class);

         System.out.println("The countries are:\n " + countries);

      } catch(Exception e) {

         e.printStackTrace();

      }

   }

}

Output

The countries are:

[INDIA, AUSTRALIA, ENGLAND, SOUTH AFRICA, WEST INDIES]

No comments:

Post a Comment