3

I try to unmarshall csv file using apache camel and bindy. I created a model with some fields annotated like this:

@DataField(pos = 5, defaultValue = "")

The problem is when my csv file contains a column with empty String. Then I got a null value as a result of unmarshalling. I would like to have empty String there as well. How should I write my annotation to get this?

Kenster
  • 23,465
  • 21
  • 80
  • 106
Peters_
  • 597
  • 2
  • 8
  • 28

2 Answers2

2

Version (2.18.0) appears to have support.

While converting the string-token (from the CSV file) to the field which was annotated by @DataField, the steps are as follow:

  1. If trim=true, trim the string-token
  2. If required and string-token is "", throw Exception
  3. Get the appropriate converter, based on the type of the field
  4. If string-token was NOT "" use the converter on the string-token
  5. else if a default-string was specified, use the converter on the default
  6. else if a java primitive (e.g. int) return an appropriate value (MIN)
  7. else return null

Version 2.18.0 introduces a new annotation @BindyConverter, allowing you to specify any class that adheres to the Format interface (effectively intercepting step #3, above)

A custom converter will allow you to read the default value and convert it according to your own requirements (in step #5 above). Your converter will also need to handle step #4, but this is trivial for Strings.

Darius X.
  • 2,886
  • 4
  • 24
  • 51
  • Thank you for the answer, but I am using Camel 2.17.0 and my test ends with error anyway: org.junit.ComparisonFailure: expected:<[]> but was:<[ ]>. It looks like trim does not work for me after reading the value. Any idea why? – Peters_ Jul 08 '16 at 08:55
  • Sorry, maybe I made a mistake here. I did run some code to test this before I answered yesterday, but cannot reproduce it now. Maybe it was something else I did when I was playing around with this. I will try again and either edit or delete my answer... depending on what I find. – Darius X. Jul 08 '16 at 13:22
  • Is it bad because i exactly need null when the string is empty and don't have anyway to do that – Michael Nov 15 '18 at 19:17
2

I followed the comment by @Darius X. and here is what worked for me:

@Column
@DataField(pos = 1, defaultValue = "default")
@BindyConverter(CustomConverter.class)
private String someField= "";

public static class CustomConverter implements Format<String> {
    @Override
    public String format(String object) {
        return "";
    }

    @Override
    public String parse(String string) {
        return "";
    }
}
hipokito
  • 413
  • 4
  • 11