JSON Tutorial

Java List to Json Using Jackson Example

Java List to Json :

Here is a simple example program for how to converting java list data into the Json file using jackson.

JavaListToJsonFile.java

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.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;
import org.codehaus.jackson.util.DefaultPrettyPrinter;

public class JavaListToJsonFile {
  public static void main(String[] args) throws JsonGenerationException,
      JsonMappingException, IOException {

    Map<String, Object> person = new HashMap<String, Object>();
    List<String> marks = new ArrayList<String>();
    person.put("name", "Arvind");
    person.put("id", "2");
    marks.add("50");
    marks.add("70");
    marks.add("60");
    person.put("Marks", marks);

    ObjectMapper mapper = new ObjectMapper();

    ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());
    writer.writeValue(new File("JacksonFile/dataThree.json"), person);
    System.out.println(person);
    System.out.println("--Done--");

  }
}

Output

–Done–