Home > other >  RESTful application using Spring boot to convert CSV to JSON
RESTful application using Spring boot to convert CSV to JSON

Time:12-07

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

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

CodePudding user response:

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;
    }
}
  • Related