Menu

SerializationExample

Benjamin Hoskins

Simple Built-In Example

@Test public void serializeObject() throws Exception {
    Person person = new Person(1001,"Mr","Forrest", Arrays.asList("Winston","Groom","Gump"), true);
    String output = Convert(person).to(String.class);
    assertThat(output, is("id=1001&title=Mr&firstName=Forrest&lastNames=Winston%2CGroom%2CGump&male=true"));
}

Hand Rolled Example

@Test public void serializeObject() throws Exception {
    Person person = new Person(1001,"Mr","Forrest", Arrays.asList("Winston","Groom","Gump"), true);
    Field[] fields = person.getClass().getDeclaredFields();
    StringBuffer b = new StringBuffer();
    for (Field field : fields) {
        field.setAccessible(true);
        b.append(field.getName()).append("=").append(Convert(field.get(person)).to(String.class)).append("&");
    }
    assertThat(b.substring(0, b.length()-1), is("id=1001&title=Mr&firstName=Forrest&lastNames=Winston,Groom,Gump&male=true"));
}




public class Person {
    private Integer id;
    private String title;
    private String firstName;
    private List<String> lastNames;
    private Boolean male;

    public Person() {}

    public Person(int id, String title, String firstName, List<String> lastNames, boolean male) {
        this.id = id;
        this.title = title;
        this.firstName = firstName;
        this.lastNames = lastNames;
        this.male = male;
    }

    public String getTitle() { return title; }
    public Boolean isMale() { return male; }
    public String getFirstName() { return firstName; }
    public List<String> getLastNames() { return lastNames; }
    public Integer getId() { return id; }
}

Related

Home: Home
Wiki: Home