Jackson provides capability to transform primitive as well as complex data types to JSON string. Here we will see List containing Map objects transformed to JSON and vice-versa.
We have simple App.java file, that contains Main method to demonstrate the capability. It has List containing Maps. Each Map holds country information.
package custom.jackson.learning;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
public class App {
public static void main(String[] args) throws Exception{
//List of country with Capital city
Map map1 = new HashMap();
map1.put("Name", "India");
map1.put("Capital", "Delhi");
map1.put("Weather", "Hot");
Map map2 = new HashMap();
map2.put("Name", "Russia");
map2.put("Capital", "Moscow");
map2.put("Weather", "Cold");
List<Map> countryList = new ArrayList<Map>();
countryList.add(map1);
countryList.add(map2);
//Convert Map to JSON
ObjectMapper mapper = new ObjectMapper();
String jsonResult = mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(countryList);
System.out.println("Convert List to JSON ::"+jsonResult);
List countryList2 = mapper.readValue(jsonResult, List.class);
System.out.println("Convert JSON to List ::"+countryList2);
}
}
Output ::
As Seen in output, in first step we transform Java List to JSON. So it converts Java List into an Array of JSON Objects. In Second steps we take JSON Array as input and convert it back to Java List containing Map objects.