Master Bidirectional JSON↔CSV Conversion in Spring Boot Quickly
This guide explains how to perform bidirectional conversion between JSON and CSV in Spring Boot using lightweight open‑source libraries such as Jackson, Apache Commons CSV or OpenCSV, as well as commercial APIs, covering serialization, deserialization, custom handling of nested objects, and provides complete code examples.
Lightweight open‑source conversion
Jackson handles JSON; Apache Commons CSV (or OpenCSV) handles CSV. In Spring Boot, @RequestBody and @ResponseBody rely on Jackson for JSON serialization/deserialization.
Core Maven dependencies
<!-- Spring Boot Web Starter (includes Jackson) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Apache Commons CSV -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.9.0</version>
</dependency>JSON ↔ Object (Jackson)
// Entity class
@Data
public class User {
private Integer id;
private String name;
private String email;
private Address address; // nested object
}
// Controller – automatic JSON ↔ object conversion
@RestController
@RequestMapping("/api/users")
public class UserController {
@PostMapping
public User createUser(@RequestBody User user) { // JSON → User
// process user …
return user; // User → JSON
}
}CSV → JSON/Object (Apache Commons CSV)
@Service
public class CsvToJsonService {
public String convertCsvToJson(InputStream csvInputStream) throws Exception {
// 1. Read CSV
BufferedReader reader = new BufferedReader(new InputStreamReader(csvInputStream));
CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.withFirstRecordAsHeader());
List<User> users = new ArrayList<>();
// 2. Map each record to a User object
for (CSVRecord record : csvParser) {
User user = new User();
user.setId(Integer.parseInt(record.get("id")));
user.setName(record.get("name"));
user.setEmail(record.get("email"));
users.add(user);
}
csvParser.close();
// 3. Serialize list to JSON string
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(users);
}
}Object/JSON → CSV (Apache Commons CSV)
@Service
public class JsonToCsvService {
public void convertJsonToCsv(List<User> users, Writer writer) throws Exception {
CSVFormat format = CSVFormat.DEFAULT.builder()
.setHeader("id", "name", "email")
.build();
CSVPrinter csvPrinter = new CSVPrinter(writer, format);
for (User user : users) {
csvPrinter.printRecord(user.getId(), user.getName(), user.getEmail());
}
csvPrinter.flush();
csvPrinter.close();
}
}Commercial / cloud conversion APIs
Aspose.Cells for Java can load a CSV file and save it directly as JSON.
import com.aspose.cells.Workbook;
import com.aspose.cells.SaveFormat;
// Load CSV and save as JSON
Workbook workbook = new Workbook("input.csv");
workbook.save("output.json", SaveFormat.JSON);GroupDocs.Conversion provides a cloud or on‑premise API that supports conversion among more than 50 formats, including CSV and JSON. Typical usage involves uploading a file, invoking conversion, and downloading the result.
Handling complex scenarios
Custom serialization : When default conversion is insufficient (e.g., a database field contains a JSON string that should be treated as a real JSON object), use Jackson’s @JsonRawValue and a custom deserializer.
Nested object conversion : CSV is flat while JSON can be nested. Converting CSV to nested JSON requires logic to combine rows or columns into sub‑objects. Converting nested JSON to CSV usually means flattening fields such as address.street and address.city into separate CSV columns.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Senior Xiao Ying
Dedicated to sharing Java backend technical experience and original tutorials, offering career transition advice and resume editing. Recognized as a rising star in CSDN's Java backend community and ranked Top 3 in the 2022 New Star Program for Java backend.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
