DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Convert CSV to XML in Java
  • How to Convert XLSX to CSV in Java
  • How to Convert Excel and CSV Documents to HTML in Java
  • The Generic Way To Convert Between Java and PostgreSQL Enums

Trending

  • Build an MCP Server Using Go to Connect AI Agents With Databases
  • Segmentation Violation and How Rust Helps Overcome It
  • How to Configure and Customize the Go SDK for Azure Cosmos DB
  • A Complete Guide to Modern AI Developer Tools
  1. DZone
  2. Coding
  3. Languages
  4. How to Convert CSV to JSON in Java

How to Convert CSV to JSON in Java

CSV data can be converted to JSON via a POJO using Jackson or, if a POJO is not defined or required, you can use the Java Collection classes.

By 
Jay Sridhar user avatar
Jay Sridhar
·
Updated Mar. 13, 17 · Tutorial
Likes (18)
Comment
Save
Tweet
Share
193.1K Views

Join the DZone community and get the full member experience.

Join For Free

CSV to JSON conversion is easy. In this article, we present a couple of methods to parse CSV data and convert it to JSON. The first method defines a POJO and uses simple string splitting to convert CSV data to a POJO, which, in turn, is serialized to JSON. The second method uses a more complete CSV parser with support for quoted fields and commas embedded within fields. In this method, we use the Java Collection classes to store the parsed data and convert those to JSON.

We use Jackson for the JSON conversion.

CSV data

Simple CSV Parsing

When the CSV file to be parsed is simple (there are no quoted fields or commas embedded in fields), you can use a simple pattern matcher to split the CSV fields.

Pattern pattern = Pattern.compile(",");


POJO Definition

We are going to parse the CSV data and create the POJO (Plain-Old-Java-Object) shown in this definition.

public class Player {
    private int year;
    private String teamId;
    private String leagueId;
    private String playerId;
    private int salary;

    public Player(int year, String teamId, String leagueId, String playerId, int salary) {
        this.year = year;
        this.teamId = teamId;
        this.leagueId = leagueId;
        this.playerId = playerId;
        this.salary = salary;
    }

    // getters and setters here 
};


Reading the CSV Data

Open the CSV file using a BufferedReader in a try-with-resources block.

try (BufferedReader in = new BufferedReader(new FileReader(csvFile));) {
    // processing code here 
}


Create the List of POJOs using a streaming pipeline. The first line is skipped because it is the CSV header. The line is split into fields using the Pattern, converted to appropriate types and used to create the object.

List<Player> players = in .lines() .skip(1) .map(line -> { 
    String[] x = pattern.split(line); 
    return new Player(Integer.parseInt(x[0]), x[1], x[2], x[3], Integer.parseInt(x[4])); }) .collect(Collectors.toList());


Serialize to JSON

Once the List is ready, use Jackson’s ObjectMapper to write the JSON. Check for full details on JSON serialization and deserialization.

ObjectMapper mapper = new ObjectMapper(); 
mapper.enable(SerializationFeature.INDENT_OUTPUT); 
mapper.writeValue(System.out, players);


And here is the whole programs segment.

Pattern pattern = Pattern.compile(",");
try (BufferedReader in = new BufferedReader(new FileReader(csvFile));) {
    List < Player > players = in .lines().skip(1).map(line - > {
        String[] x = pattern.split(line);
        return new Player(Integer.parseInt(x[0]), x[1], x[2], x[3], Integer.parseInt(x[4]));
    }).collect(Collectors.toList());
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.writeValue(System.out, players);
}


CSV to JSON Conversion (No POJO)

In this example, we use the CSV parser presented in this article. This CSV parser can handle multi-line quoted fields and commas embedded within fields, just like Excel can. It uses the first line of the CSV file as field names and loads the data into a List, which is then exported to JSON.

Here is the complete segment.

try (InputStream in = new FileInputStream(csvFile);) {
    CSV csv = new CSV(true, ',', in );
    List < String > fieldNames = null;
    if (csv.hasNext()) fieldNames = new ArrayList < > (csv.next());
    List < Map < String, String >> list = new ArrayList < > ();
    while (csv.hasNext()) {
        List < String > x = csv.next();
        Map < String, String > obj = new LinkedHashMap < > ();
        for (int i = 0; i < fieldNames.size(); i++) {
            obj.put(fieldNames.get(i), x.get(i));
        }
        list.add(obj);
    }
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.writeValue(System.out, list);
}


Here is a part of the CSV data that was converted:

rep_file_num,CIK,entity_name,street1,street2,city,state_code,zip,filing_date,doc_type_code 
814-00034,0000731812,SIERRA RESOURCES CORP,629 J STREET,SUITE 202,SACRAMENTO,CA,95814,12/30/96,15 
814-00053,0000821472,WESTFORD TECHNOLOGY VENTURES LP,17 ACADEMY ST 5TH FLOOR,[NULL],NEWARK,NJ,07102-2905,01/28/04,NO ACT ... 
814-00098,0000878932,"EQUUS TOTAL RETURN, INC.",EIGHT GREENWAY PLAZA,SUITE 930,HOUSTON,TX,77046,08/25/16,40-APP/A


Notice that one of the fields in the data is quoted because of embedded commas. Here is the converted JSON for that record, which shows that the record has been parsed and converted correctly.

{ 
    "rep_file_num" : "814-00098", 
    "CIK" : "0000878932", 
    "entity_name" : "EQUUS TOTAL RETURN, INC.", 
    "street1" : "EIGHT GREENWAY PLAZA", 
    "street2" : "SUITE 930", 
    "city" : "HOUSTON", 
    "state_code" : "TX", 
    "zip" : "77046", 
    "filing_date" : "08/25/16", 
    "doc_type_code" : "40-APP/A" 
}

Summary

CSV data can be converted to JSON via a POJO using Jackson. If a POJO is not already defined or required, you can always use the Java Collection classes to store parsed data and later convert it to JSON.

JSON CSV Convert (command) Java (programming language) Data (computing)

Published at DZone with permission of Jay Sridhar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Convert CSV to XML in Java
  • How to Convert XLSX to CSV in Java
  • How to Convert Excel and CSV Documents to HTML in Java
  • The Generic Way To Convert Between Java and PostgreSQL Enums

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!