Convert Java Object To / From JSON, Jackson Example

A complete example is below

Jackson JSON Example

package net.javatips;

import java.io.File;
import java.io.IOException;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class Main {

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

     
ObjectMapper mapper = new ObjectMapper();
      Student student =
new Student();      
      // stored into student.json file
   
  mapper.writeValue
(new File("student.json"), student);

      student = mapper.readValue
(new File("student.json"), Student.class);      
      // disply in console
   
  System.out.println
("student details" + student);

  
}
}
Output (student.json)
{"firstName":"Rockey","lastName":"Desousa"}
Console output
student details Student [firstName=Rockey, lastName=Desousa]

Jackson JSON Pretty Print

If you need to formatt the JSON string, you can use the following method

ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();

A complete example is below

package net.javatips;

import java.io.IOException;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;

public class Main {

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

     
ObjectMapper mapper = new ObjectMapper();
      Student student =
new Student();
     
      ObjectWriter ow = mapper.writer
().withDefaultPrettyPrinter();
      String prettyJsonStudent = ow.writeValueAsString
(student);

      System.out.println
(prettyJsonStudent);

  
}
}
Output
{
  "firstName" : "Rockey",
  "lastName" : "Desousa"
}

 





Previous 1 2








Your email address will not be published. Required fields are marked *