In this tutorial we see how to convert Map to Json file by using Jackson Api.
Let us have a look in to the below code example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
package com.connect2java.JacksonMapToJsonExample; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.ObjectMapper; public class JacksonMapToJsonExample { public static void main(String[] args) { Map<String, Object> map = new HashMap<String, Object>(); map.put("bankName", "ICICI"); map.put("code", "ICICI00001"); List<Object> branches = new ArrayList<Object>(); branches.add("India"); branches.add("US"); branches.add("China"); map.put("branches", branches); try { ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(new File("e:\\bank.json"), map); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } |
NOTE : Please include the “jackson-all-1.8.2.jar” in class path to avoid errors.
OUTPUT: Check the E: drive , bank.json will be created and the content would be like as below.
1 2 3 4 5 |
{"bankName":"ICICI","code":"ICICI00001","branches":["India","US","China"]} |
Happy Learning … 🙂