Bean To JSON
JSON (JavaScript Object Notation) is a lightweight text-based open standard
designed for human-readable data interchange.
Douglas Crockford has provided a reference implementation of JSON in Java at
http://json.org/ useful for JSON
serialization and deserialization.
Click here
to download the compiled library.
The following example shows serializing a bean to JSON string.
package com.bethecoder.tutorials.json_java.common;
import java.util.Date;
public class Student {
private String firstName;
private String lastName;
private int age;
private String hobby;
private Date dob;
public Student ( String firstName, String lastName, int age, String hobby,
Date dob ) {
super () ;
this .firstName = firstName;
this .lastName = lastName;
this .age = age;
this .hobby = hobby;
this .dob = dob;
}
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;
}
public int getAge () {
return age;
}
public void setAge ( int age ) {
this .age = age;
}
public String getHobby () {
return hobby;
}
public void setHobby ( String hobby ) {
this .hobby = hobby;
}
public Date getDob () {
return dob;
}
public void setDob ( Date dob ) {
this .dob = dob;
}
}
package com.bethecoder.tutorials.json_java.tests;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;
import com.bethecoder.tutorials.json_java.common.Student;
public class Bean2Json {
/**
* @param args
* @throws JSONException
*/
public static void main ( String [] args ) throws JSONException {
Student stud = new Student ( "Sriram" , "Kasireddi" , 2 , "Singing" , new Date ( 110 , 4 , 6 )) ;
JSONObject obj = new JSONObject ( stud ) ;
System.out.println ( obj.toString ( 2 )) ; //pretty print with indent
}
}
It gives the following output,
{
"lastName": "Kasireddi",
"dob": "Thu May 06 00:00:00 IST 2010",
"age": 2,
"hobby": "Singing",
"firstName": "Sriram"
}