JSON > FLEX JSON > How to Control Serialization through Annotations
How to Control Serialization through Annotations
Flexjson is a lightweight java library for serializing and de-serializing
java beans, maps, arrays and collections in JSON format.
Get the latest binaries from
https://sourceforge.net/projects/flexjson/ .
This requires the library flexjson-2.1.jar to be in classpath.
The following example shows how to control the Serialization through Flexjson Annotations.
package com.bethecoder.tutorials.flexjson.common;
import java.util.Date;
import flexjson.JSON;
public class Student2 {
private String firstName;
private String lastName;
private int age;
private String hobby;
private Date dob;
public Student2 ( 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;
}
@JSON ( include= false )
public int getAge () {
return age;
}
public void setAge ( int age ) {
this .age = age;
}
@JSON //or @JSON(include=true) default values is true
public String getHobby () {
return hobby;
}
public void setHobby ( String hobby ) {
this .hobby = hobby;
}
@JSON ( include= false )
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.flexjson.tests;
import java.util.Date;
import com.bethecoder.tutorials.flexjson.common.Student2;
import flexjson.JSONSerializer;
public class AnnotationsTest {
/**
* @param args
*/
public static void main ( String [] args ) {
JSONSerializer serializer = new JSONSerializer () .prettyPrint ( true ) ;
Student2 stud = new Student2 ( "Sriram" , "Kasireddi" , 2 , "Singing" , new Date ()) ;
String jsonStr = serializer.serialize ( stud ) ;
System.out.println ( jsonStr ) ;
}
}
It gives the following output,
{
"firstName": "Sriram",
"hobby": "Singing",
"lastName": "Kasireddi"
}