使用双引号键/值将csv字符串转换为Map

时间:2019-02-19 23:02:24

标签: java csv collections jackson

我正在将CSV字符串转换为Map。我可以将其转换,但是问题是我需要在Map中使用双引号""

获取键和值
  

输入字符串:“ fname”,“ lname”,...... \ n   “ ramprakash”,“ seepana”,...

     

获取数据[fname = ramprakash,lname = seepana,...]

     

期望的数据是:[“ fname” =“ ramprakash”,“ lname” =“ seepana”,...]

如何实现?

2 个答案:

答案 0 :(得分:0)

处理CSV univocity-parsers是最好的选择。它也比其他任何解析器faster都要多。

尝试以下代码:

String input = "'fname','lname'\n'ramprakash','seepana'\n";

CsvParserSettings settings = new CsvParserSettings(); //many options here, check the tutorial
settings.setHeaderExtractionEnabled(true); //use first row as headers
settings.getFormat().setQuote('\''); //using single quotes for clarity

settings.setKeepQuotes(true); //keep the quotes

CsvParser parser = new CsvParser(settings);
for (Record record : parser.iterateRecords(new StringReader(input))) {
    Map<String, String> map = record.toFieldMap();
    System.out.println(map);
}

输出:

{fname='ramprakash', lname='seepana'}

希望这会有所帮助

编辑:

我只是注意到标题不会用引号引起来(通常是人们想要的)。您仍然可以使用引号将所有内容显示为普通行并自己填写地图:

    String input = "'fname','lname'\n'ramprakash','seepana'\n'I won\\'t go away'";

    CsvParserSettings settings = new CsvParserSettings();
    settings.getFormat().setQuote('\'');
    settings.getFormat().setQuoteEscape('\\'); //added escape quote character too

    settings.setKeepQuotes(true);
    settings.setKeepEscapeSequences(true); //you probably want this

    CsvParser parser = new CsvParser(settings);
    for (String[] row: parser.iterate(new StringReader(input))) {
        System.out.println(Arrays.toString(row));
    }

打印:

['fname', 'lname']
['ramprakash', 'seepana']
['I won\'t go away']

披露:我是这个图书馆的作者。它是开源且免费的(Apache V2.0许可证)

答案 1 :(得分:0)

假设您的CSV如下所示:

"fname", "lname"
"ramprakash","seepana"
"ramprakash1","seepana1"

要拥有",您需要在CsvSchema中禁用引号字符。示例:

import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;

import java.io.File;
import java.util.Map;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        File csv = new File("./resource/test.csv").getAbsoluteFile();

        CsvMapper mapper = new CsvMapper();

        CsvSchema schema = CsvSchema
                .emptySchema()
                .withHeader()
                .withColumnSeparator(',')
                .withoutQuoteChar();

        MappingIterator<Map<String, String>> it = mapper
                .readerFor(Map.class)
                .with(schema)
                .readValues(csv);


        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }
}

上面的代码显示:

{"fname"="ramprakash", "lname"="seepana"}
{"fname"="ramprakash1", "lname"="seepana1"}