簡體   English   中英

將單個CSV / TSV字符串轉換為Java對象?

[英]Converting a single CSV/TSV string into a Java object?

不是將整個CSV文件轉換為對象,而是有一個簡單的API接受一個csv或tsv字符串,然后將其轉換為對象? 到目前為止,我發現的api是針對csv / tsv的對象列表。

顯然,我可以拆分String並調用構造函數,但是想知道是否可以使用干凈的api。

您可以和Jackson一起做。 它看起來與其他答案非常相似,但根據他們的測試 ,它們似乎比SuperCSV更好。

定義您的POJO(注解和構造函數似乎都是必需的):

@JsonPropertyOrder({ "foo", "bar" })
public class FooBar {

    private String foo;
    private String bar;

    public FooBar() {
    }

    // Setters, getters, toString()
}

然后解析它:

String input = "1,2\n3,4";
StringReader reader = new StringReader(input);
CsvMapper m = new CsvMapper();
CsvSchema schema = m.schemaFor(FooBar.class).withoutHeader().withLineSeparator("\n").withColumnSeparator(',');
try {
    MappingIterator<FooBar> r = m.reader(FooBar.class).with(schema).readValues(reader);
    while (r.hasNext()) {
        System.out.println(r.nextValue());
    }

} catch (JsonProcessingException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

使用uniVocity解析器,因為它的速度至少是SuperCSV的兩倍,並且具有更多功能。

例如,假設您的bean是:

class TestBean {

// if the value parsed in the quantity column is "?" or "-", it will be replaced by null.
@NullString(nulls = { "?", "-" })
// if a value resolves to null, it will be converted to the String "0".
@Parsed(defaultNullRead = "0")
private Integer quantity;   // The attribute type defines which conversion will be executed when processing the value.
// In this case, IntegerConversion will be used.
// The attribute name will be matched against the column header in the file automatically.

@Trim
@LowerCase
// the value for the comments attribute is in the column at index 4 (0 is the first column, so this means fifth column in the file)
@Parsed(index = 4)
private String comments;

// you can also explicitly give the name of a column in the file.
@Parsed(field = "amount")
private BigDecimal amount;

@Trim
@LowerCase
// values "no", "n" and "null" will be converted to false; values "yes" and "y" will be converted to true
@BooleanString(falseStrings = { "no", "n", "null" }, trueStrings = { "yes", "y" })
@Parsed
private Boolean pending;

現在,將您的輸入作為TestBean的列表進行TestBean

// BeanListProcessor converts each parsed row to an instance of a given class, then stores each instance into a list.
BeanListProcessor<TestBean> rowProcessor = new BeanListProcessor<TestBean>(TestBean.class);

CsvParserSettings parserSettings = new CsvParserSettings();
parserSettings.setRowProcessor(rowProcessor);
parserSettings.setHeaderExtractionEnabled(true);

CsvParser parser = new CsvParser(parserSettings);
parser.parse(getReader("/examples/bean_test.csv"));

// The BeanListProcessor provides a list of objects extracted from the input.
List<TestBean> beans = rowProcessor.getBeans();

要解析TSV文件,只是改變的組合CsvParserSettingsCsvParserTsvParserSettingsTsvParser

披露:我是這個圖書館的作者。 它是開源且免費的(Apache V2.0許可證)。

我正在使用這個API: http//jsefa.sourceforge.net/

您可以使用注釋將您的實體轉換為CSV。

如果您在注釋中提到了SuperCSV,則可以將包裝在StringReaderString傳遞給它,即

CsvBeanReader beanReader=new CsvBeanReader(new StringReader(theString), preferences);

beanReader.read(theBean, nameMapping);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM