Red Hat Training

A Red Hat training course is available for Red Hat Fuse

2.6. Binding CSV Records to Java Objects

  1. Read the following to learn how to CSV records to Java objects. In this example, we will use CSV records for people:
    Tom,Fennelly,Male,4,Ireland
    Mike,Fennelly,Male,2,Ireland
    
  2. Input this code to bind the record to a person:
    
    public class Person {
        private String firstname;
        private String lastname;
        private String country;
        private Gender gender;
        private int age;
    }
     
    public enum Gender {
        Male, 
        Female;
    }
    
    
  3. Input the following code and modify it to suit your task:
    
    <?xml version="1.0"?>
    <smooks-resource-list xmlns="http://www.milyn.org/xsd/smooks-1.1.xsd" xmlns:csv="http://www.milyn.org/xsd/smooks/csv-1.2.xsd">
     
        <csv:reader fields="firstname,lastname,gender,age,country">
            <!-- Note how the field names match the property names on the Person class. -->
            <csv:listBinding beanId="people" class="org.milyn.csv.Person" />
        </csv:reader>
     
    </smooks-resource-list>
    
  4. To execute the configuration, use this code:
    
    Smooks smooks = new Smooks(configStream);
    JavaResult result = new JavaResult();
     
    smooks.filterSource(new StreamSource(csvStream), result);
     
    List<Person> people = (List<Person>) result.getBean("people");
    
  5. You can create Maps from the CSV record set:
    
    <?xml version="1.0"?>
    <smooks-resource-list xmlns="http://www.milyn.org/xsd/smooks-1.1.xsd" xmlns:csv="http://www.milyn.org/xsd/smooks/csv-1.2.xsd">
     
        <csv:reader fields="firstname,lastname,gender,age,country">
            <csv:mapBinding beanId="people" class="org.milyn.csv.Person" keyField="firstname" />
        </csv:reader>
     
    </smooks-resource-list>
    
    
  6. The configuration above produces a map of person instances, keyed to the firstname value of each person. This is how it is executed:
    
    Smooks smooks = new Smooks(configStream);
    JavaResult result = new JavaResult();
     
    smooks.filterSource(new StreamSource(csvStream), result);
     
    Map<String, Person> people = (Map<String, Person>) result.getBean("people");
     
    Person tom = people.get("Tom");
    Person mike = people.get("Mike");
    
    
    Virtual models are also supported, so you can define the class attribute as a java.util.Map and bind the CSV field values to map instances which are, in turn, added to a list or map.