开发者

RESTful application using Spring boot to convert CSV to JSON

开发者 https://www.devze.com 2022-12-07 20:27 出处:网络
I am looking to build a Restful application using Spring Boot to convert CSV items to JSON objects and I want开发者_JS百科 to understand the best approach to do it.

I am looking to build a Restful application using Spring Boot to convert CSV items to JSON objects and I want开发者_JS百科 to understand the best approach to do it.

If CSV or CSV items can be passed through getMapping() method and then converted to JSON.


The best approach would be using POST Mapping, GET Mapping is not considered a good approach. Also I am using jackson library to read csv file and conversion as it make lot of things easier. Hope this generic code will help.

Controller

@PostMapping("/api/file-upload")
public ResponseEntity<String> uploadSingleFile (@RequestParam("csvFile") MultipartFile csvFile) {
  try{        
    serviceClass.convertCsvToJson(csvFile);
    return ResponseEntity.status(HttpStatus.OK).body("File uploaded");
  }catch(Exception e){
     return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("File upload failed");
  }         
}

Service class method

public void convertCsvToJson(MultipartFile csvFile){
CsvSchema csvSchema = CsvSchema.emptySchema().withHeader();
CsvMapper csvMapper = new CsvMapper();
try {
        List<Map<?, ?>> list;
        try (MappingIterator<Map<?, ?>> mappingIterator = csvMapper.reader()
                .forType(Map.class)
                .with(csvSchema)
                .readValues(csvFile)) {
            list = mappingIterator.readAll();
        }

        ObjectMapper objectMapper = new ObjectMapper();
        // You can also map csv content to you own pojo
        String jsonPretty = objectMapper.writerWithDefaultPrettyPrinter()
                .writeValueAsString(list);
                
        // Do something with json string        
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号