Bean to JSON Exclude Filter
JSON-lib is a java library for serializing and de-serializing
java beans, maps, arrays and collections in JSON format.
Get the latest binaries from sourceforge
http://json-lib.sourceforge.net/ .
This requires the libraries (
json-lib-2.4-jdk15.jar, xom-1.2.7.jar, ezmorph.jar
commons-lang.jar, commons-collections.jar, commons-beanutils-1.7.jar and
commons-logging-1.1.1.jar ) to be in classpath.
The following example shows converting a bean to JSON Object using exclude filter.
package com.bethecoder.tutorials.json_lib.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 () {
}
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;
}
public String toString () {
return "Student[ " +
"firstName = " + firstName +
", lastName = " + lastName +
", age = " + age +
", hobby = " + hobby +
", dob = " + dob +
" ]" ;
}
}
package com.bethecoder.tutorials.json_lib.tests;
import java.util.Date;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;
import com.bethecoder.tutorials.json_lib.common.Student;
public class Bean2JsonExcludeFilter {
/**
* @param args
*/
public static void main ( String [] args ) {
Student stud = new Student ( "Sriram" , "Kasireddi" , 2 , "Singing" , new Date ( 110 , 4 , 6 )) ;
JsonConfig jsonConfig = new JsonConfig () ;
jsonConfig.setJsonPropertyFilter ( new PrimitevePropertyFilter ()) ;
JSONObject obj = JSONObject.fromObject ( stud, jsonConfig ) ;
System.out.println ( obj.toString ( 2 )) ; //pretty print with indent
}
}
class PrimitevePropertyFilter implements PropertyFilter {
@Override
public boolean apply ( Object source, String name, Object value ) {
//System.out.println("name = " + name + ", value = " + value);
if ( Number. class .isAssignableFrom ( value.getClass ()) ||
String. class .isAssignableFrom ( value.getClass ()) ) {
return false ;
}
return true ;
}
}
It gives the following output,
{
"age": 2,
"firstName": "Sriram",
"hobby": "Singing",
"lastName": "Kasireddi"
}