42BV / CSVeed

Light-weight, easy-to-use Java-based CSV utility
Apache License 2.0
100 stars 22 forks source link

Support T/F Y/N as boolean #120

Closed lrkwz closed 1 year ago

lrkwz commented 4 years ago

I understand that CustomBooleanConverter() can be initialized with a custom string for TRUE and one for FALSE but it could be the case of "multiple trues and falses" such if you want to support both T/F and Y/N complementing TRUE/FALSE and YES/NO.

Is there a way to implement it out-of-the-box?

lrkwz commented 3 years ago

If of any use here is my custom converter

import org.csveed.bean.conversion.CustomBooleanConverter;

public class ItalianizedCustomBooleanConverter extends CustomBooleanConverter {

    public static final String VALUE_SI = "si";
    public static final String VALUE_SHORT_SI = "S";

    public static final String VALUE_SHORT_TRUE = "T";
    public static final String VALUE_SHORT_FALSE = "F";

    public static final String VALUE_SHORT_YES = "Y";
    public static final String VALUE_SHORT_NO = "N";

    public ItalianizedCustomBooleanConverter(boolean allowEmpty) {
        super(null, null, allowEmpty);
    }

    public ItalianizedCustomBooleanConverter(String trueString, String falseString,
            boolean allowEmpty) {
        super(trueString, falseString, allowEmpty);
    }

    @Override
    public Boolean fromString(String input) throws Exception {
        if (input != null
            && (VALUE_SI.equalsIgnoreCase(input.trim())
            || VALUE_SHORT_SI.equalsIgnoreCase(input)
            || VALUE_SHORT_TRUE.equalsIgnoreCase(input))
            || VALUE_SHORT_YES.equalsIgnoreCase(input)) {
            return Boolean.TRUE;
        } else if ((VALUE_SHORT_FALSE.equalsIgnoreCase(input))
            || VALUE_SHORT_NO.equalsIgnoreCase(input)) {
            return Boolean.FALSE;
        } else {
            return super.fromString(input);
        }
    }

}
hazendaz commented 1 year ago

Taking a variation of this. I'm making a few assumptions as I haven't directly worked with the code in a while. But believe the fromString is used to set the internal true/false/allow empty logic. Design here is a bit funny and sonar is calling part of it out. At any rate, I think in this case, I don't want the Italian part as we could go crazy there with various languages. Instead, I've found T|F and and Y|N for years throughout code so those make the most sense. As such, to the 'fromString', I've added such support. Currently there were no tests directly testing the existing let alone new and that I think says for now as code overwise is straight forwards.

hazendaz commented 1 year ago

fixed via #174