通过json模式将map转换为json字符串 [英] Convert map to json string by json schema
问题描述
是否可以通过json模式将地图转换为json字符串?我需要通过json模式执行此操作,因为我不知道映射中的对象是字符串还是数字.例如,我的csv如下所示:
Is there a way to convert the map to json string by json schema? I need to do that by json schema because I don't know if the object in the map is a string or a number. For example, I have csv that look like this:
name, year
1 , 1
我需要将其转换为json字符串"{'name': '1', 'year': 1}"
,仅通过json模式,我就可以知道1是字符串(在名称中)还是数字(在年份中).
I need to convert it to json string "{'name': '1', 'year': 1}"
and I can know if 1 is a string (in a case of the name) or number (in a case of the year) only by json schema.
推荐答案
您可以使用Jackson尝试类似的方法:
You could try something like this using Jackson:
您唯一需要自己实现的方法是将CsvSchema.json转换为包含列名和列类型的Map的第二种方法.
The only thing you need to implement by yourself is the second method to convert your CsvSchema.json to a Map containing the column name and the column type.
public String generateJsonFromCSV() throws IOException {
File csvFile = new File("path/to/csv/mycsv.csv");
File schemaJson = new File("path/to/json/schema.json");
Map<String, CsvSchema.ColumnType> map = getSchemaMapFromJson(schemaJson);
CsvSchema.Builder schemaBuilder = new CsvSchema.Builder();
map.forEach(schemaBuilder::addColumn);
CsvSchema schema = schemaBuilder.build();
CsvMapper csvMapper = new CsvMapper();
MappingIterator<Map<?, ?>> mappingIterator = csvMapper.readerFor(Map.class).with(schema).readValues(csvFile);
String json = new ObjectMapper().writeValueAsString(mappingIterator.readAll());
return json;
}
//Convert your JsonSchema to Map<String,CsvSchema.ColumnType>
private Map<String, CsvSchema.ColumnType> getSchemaMapFromJson(File file) {
return new HashMap<>();
}
依赖性:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-csv</artifactId>
<version>${jackson.version}</version>
</dependency>
这篇关于通过json模式将map转换为json字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!