有没有办法通过 json schema 将 map 转换为 json 字符串?我需要通过 json 模式来做到这一点,因为我不知道 map 中的对象是字符串还是数字。例如,我的 csv 看起来像这样:
name, year
1 , 1
我需要将其转换为 json 字符串 "{'name': '1', 'year': 1}"
我可以知道 1 是否是一个字符串(在名称)或数字(如果是年份)仅通过 json 模式。
最佳答案
jackson 有一个 module to parse CSV文件。假设您的项目中已经有 Jackson 依赖项,您只需添加以下依赖项:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-csv</artifactId>
<version>${jackson.version}</version>
</dependency>
然后创建一个类来定义架构并保存值(请注意 @JsonPropertyOrder
注释,因为它定义了 CSV 列的顺序):
@JsonPropertyOrder({"name", "year"})
public class Person {
private String name;
private Integer year;
// Getters and setters
}
将 CSV 文档解析为列表,最后将列表写入 JSON 字符串:
CsvMapper mapper = new CsvMapper();
CsvSchema schema = mapper.schemaFor(Person.class).withHeader();
MappingIterator<Object> iterator = mapper.readerFor(Person.class)
.with(schema).readValues(new FileInputStream("/path/to/the/csv/file"));
String json = new ObjectMapper().writeValueAsString(iterator.readAll());
关于java - 通过 json schema 将 map 转换为 json 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55064706/