How to do typecasting before parsing csv field to java object

552 Views Asked by At

I have a CSV file like below

Rahul|S|74|72|71
Amrit|S|82|81|80
Akshay|S|82|89|81

And i want to map the fields to a java object. I am getting all the fields as String in the file. I am converting them to java object using opencsv like below

My student class will look like:

public class Student {
  @CsvBindByPosition(position = 0)
  private String name;

  @CsvBindByPosition(position = 1)
  private String mathsScore;

  @CsvBindByPosition(position = 2)
  private String scienceScore;

  @CsvBindByPosition(position = 3)
  private String englishScore;
}

And this is how i am parsing it to Student object.

List<Student> studentsList = new CSVToBeanBuilder(new FileReader(csvFile))
      .withType(Student.class)
      .build().parse();

I am parsing the csv fields to java object because i want to store them in database And in my database marks are Integer but i am getting them as String in csv file.

Right now in Student class i have defined marks as String because i am getting them as String in csv file. Is there any way to typecast marks to Integer directly while parsing them to Student object so that i can use same Student class to save in DB, otherwise i will have to create another class unnecessarily.

1

There are 1 best solutions below

1
On BEST ANSWER

You can use both Integer and int when defining the field.

Example below:

    @CsvBindByPosition(position = 0)
    public String macAddress;

    @CsvBindByPosition(position = 1)
    public int seqID;

    @CsvBindByPosition(position = 2)
    public Integer digital1;

    @CsvBindByPosition(position = 3)
    public Integer digital2;

    @CsvBindByPosition(position = 4)
    public Integer digital3;

    @CsvBindByPosition(position = 5)
    public Integer digital4;

    @CsvBindByPosition(position = 6)
    public Double col1;

    @CsvBindByPosition(position = 7)
    public Double col2;

    @CsvBindByPosition(position = 8)
    public Double col3;

    @CsvBindByPosition(position = 9)
    public Double col4;

    @CsvBindByPosition(position = 10)
    public Double col5;

    @CsvBindByPosition(position = 11)
    public Double col6;

    @CsvBindByPosition(position = 12)
    public Long timeStamp;

--- Edited ---

For Date:

@CsvBindByPosition(position = 2)
@CsvDate(value = "dd.MM.yyyy")
private Date birthDate;