How to convert a java object to Json string

To convert an object to json string we can use jackson api.latest jackson  api  requires jackson-annotations-2.2.2.jar,jackson-core-2.2.2.jar,jackson-databind-2.2.2.jar

Consider below employee class

public class Employee {
    
    private String name;
    private int id;
     
    public Employee(String n, int id){
        this.name = n;
        this.id = id;
    }
     
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getID() {
        return id;
    }
    public void setID(int id) {
        this.id = id;
    }
    public String toString(){
        return "Name: "+this.name+" <<==>>ID: "+this.id;
    }
}

Converting employee class object to json string.

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ObjectToJsonExample {
    
    public static void main(String[] args) throws JsonProcessingException {
        
    String outString=null;    
    Employee emp=new Employee("test", 10);
    ObjectMapper mapper=new ObjectMapper();
    
    outString=mapper.writeValueAsString(emp);
    System.out.println(outString);
       
    } 

}

Output:

{"name":"test","id":10}

How To convert list of objects to json string

import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ObjectToJsonExample {
    
    public static void main(String[] args) throws JsonProcessingException {
        
    String outString=null;
    List list=new ArrayList();
    ObjectMapper mapper=new ObjectMapper();
    
    Employee emp1=new Employee("test1", 101);
    Employee emp2=new Employee("test2", 102);
    Employee emp3=new Employee("test3", 103);
    
    list.add(emp1);
    list.add(emp2);
    list.add(emp3);
    outString=mapper.writeValueAsString(list);
    System.out.println(outString);
      
    } 

}

Output:

[{"name":"test1","id":101},{"name":"test2","id":102},{"name":"test3","id":103}]
Advertisements
This entry was posted in Java. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s