gpt4 book ai didi

java - 将 csv 字符串转换为带有双引号键/值的 Map

转载 作者:行者123 更新时间:2023-12-02 10:14:29 25 4
gpt4 key购买 nike

我正在努力将 CSV 字符串转换为 Map。我可以转换它,但问题是我需要使用双引号获取 Map 中的键和值""

input string: "fname", "lname", ...... \n "ramprakash","seepana",...

Getting data [fname=ramprakash, lname=seepana, ...]

Expected data is: ["fname"="ramprakash", "lname"="seepana", ...]

如何实现这一目标?

最佳答案

假设您的 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"}

关于java - 将 csv 字符串转换为带有双引号键/值的 Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54776233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com