Convert Java Object To / From JSON, Jackson Example

Convert Java Object To / From JSON, Jackson Example explains about converting a Java Object to JSON string, JSON string to Java Object Using Jackson JSON library

Consider an example where you need to pass the request as JSON string, In this situation you can easily serialize the Java Object to JSON string and vice versa

According to Jackson documentation, Jackson is a multi-purpose Java library for processing JSON data format. Jackson aims to be the best possible combination of fast, correct, lightweight, and ergonomic for developers.

Reference -> https://github.com/FasterXML/jackson/

Here I am showing an example about How to convert a Java Object to JSON string and vice versa using Jackson processor.

Required Libraries

You need to download

  1. jackson

Following jar must be in classpath

  1. jackson-all-1.9.11.jar

Project structure

Convert Java Object To JSON Using Jackson

Student.java

Here I am creating a pojo class, this will be the converted in to JSON string.

package net.javatips;

public class Student {

  
private String firstName="Rockey";
  
private String lastName="Desousa";

  
public String getFirstName() {
     
return firstName;
  
}

  
public void setFirstName(String firstName) {
     
this.firstName = firstName;
  
}

  
public String getLastName() {
     
return lastName;
  
}

  
public void setLastName(String lastName) {
     
this.lastName = lastName;
  
}

  
@Override
  
public String toString() {
     
return "Student [firstName=" + firstName + ", lastName=" + lastName + "]";
  
}
  
}

Convert Java Student Object to JSON string

For converting Java Student Object to JSON string, you can use following method, Here student.json is a file

mapper.writeValue(new File("student.json"), student);

Convert JSON string to Java Student Object

For converting JSON string to Java Student Object, you can use following method

student = mapper.readValue(new File("student.json"), Student.class);
1 2 Next





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