Bean to CSV
SOJO (S implified O ld J ava O bjects) is a Java framework
which converts object graph into a specific structure or representation.
This requires the library sojo-1.0.0.jar to be in classpath.
The following example shows using CsvSerializer class.
It converts the given bean to CSV.
package com.bethecoder.tutorials.sojo.common;
public class Student {
private String name;
private int age;
private String hobby;
public Student () {
}
public Student ( String name, int age, String hobby ) {
super () ;
this .name = name;
this .age = age;
this .hobby = hobby;
}
public String getName () {
return name;
}
public void setName ( String name ) {
this .name = name;
}
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 String toString () {
return "Student[name = " + name + ", age = " + age + ", hobby = " + hobby + "]" ;
}
}
package com.bethecoder.tutorials.sojo.tests;
import java.io.IOException;
import net.sf.sojo.interchange.Serializer;
import net.sf.sojo.interchange.csv.CsvSerializer;
import com.bethecoder.tutorials.sojo.common.Student;
public class Bean2CSV {
/**
* @param args
*/
public static void main ( String [] args ) throws IOException {
Student student = new Student ( "Sriram" , 2 , "Chess" ) ;
Serializer serializer = new CsvSerializer () ;
String str = ( String ) serializer.serialize ( student ) ;
System.out.println ( "Generated CSV : \n" ) ;
System.out.println ( str ) ;
}
}
It gives the following output,
Generated CSV :
~unique-id~,hobby,class,name,age
0,Chess,com.bethecoder.tutorials.sojo.common.Student,Sriram,2