Way To Java

Way To Java

Share

01/08/2017

Convert Java object to JSON
---------------------------------------
- Jackson API is used to convert java object to JSON.
- Set class path of jackson.jar file.
- Jackson API provides a class ObjectMapper, that having method writeValueAsString().
- String writeValueAsString(Object obj)
- This method takes object as argument and returns String representation of JSON
- Remember java class must implements Serializable interface whose object we want to convert into JSON.
- Jackson API can access only those data members that are public, but it is not possible to make each and every instance member as public. Hence create getter() and setter() of that class.
--------------
Example :
--------------
Employee.java
--------------------
import org.codehaus.jackson.map.ObjectMapper;
import java.io.Serializable;

class Employee implements Serializable{
private int id;
private String name;
private int salary;

public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public int getSalary(){
return salary;
}
public void setSalary(int salary){
this.salary = salary;
}
}

Test.java
------------
class Test{
public static void main(String[]args){
Employee emp = new Employee();
emp.setId(1002);
emp.setName("Mukesh Kumar");
emp.setSalary(20000);
try{
ObjectMapper mapper = new ObjectMapper();
String jsonObject = mapper.writeValueAsString(emp);
System.out.println("Employee Object In JSON Form : "+ jsonObject);
}catch(Exception e){
System.out.println(e);
}
}
}

Output -
-----------
Employee Object In JSON Form : {"id":1002,"name":"Mukesh Kumar","salary":20000}

Want your school to be the top-listed School/college in Noida?
Click here to claim your Sponsored Listing.

Category

Address


Noida