Search code examples
csvunivocity

Univocity parser - parse csv row into existing bean instance


I'm trying to parse a csv file into new and existing instances of a bean, using univocity parser. The csv is generated by using univocity BeanWriterProcessor, for a set of beans that I will call set A.

Now I want to read the csv back, doing the following:

Case 1: if the row corresponds to a bean which was originally present in set A, I do not want to create a new bean instance, but instead read the csv into the "existing" instance. (i.e., "update" the instance). I check existence by using the UUID of the bean.

Case 2: if the row does not correspond to a bean originally present in set A, I want to create a new bean instance for it.

Problem I want to solve: for Case 1, how can I write to an existing bean instance?

In supercsv, I could do it with something like that:

beanReader.read(targetExistingBean, header, processors);

How can I do this in univocity?


Solution

  • Currently, the only way to do it would be by overriding the createBean method of BeanProcessor or BeanListProcessor (whichever you are using):

    BeanListProcessor<Car> carProcessor = new BeanListProcessor<Car>(Car.class){
        @Override
        public Car createBean(String[] row, Context context) {
            //analyze the row here to determine whether to return an existing instance
            //if you need a new instance, call super.createBean(row, context);
        }
    };
    

    Hope this helps.