JSON Tutorial

Java String to Json using Jackson Example

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

JavaStringToJsonFile.java

package com.JasonProjectDeomo.Jackson.JsonWrite;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
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.map.SerializationConfig;
import org.codehaus.jackson.util.DefaultPrettyPrinter;

import com.JasonProjectDeomo.bean.Person;

public class JavaStringToJsonFile {

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

    // read from string variable
    String json = "{\"id\":1,\"name\":\"Arvind\",\"address\":{\"village\":\"Dhananjaypur\",\"district\":\"Varanasi\",\"state\":\"UP\"}}";

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationConfig.Feature.AUTO_DETECT_FIELDS, true);
    Person person = mapper.readValue(json, Person.class);

    mapper.writeValue(new File("JacksonFile/dataOne.json"), person);
    System.out.println(json);
    System.out.println("--Done--");
  }
}

Output:

–Done–