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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
  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.

Jay Sridhar user avatar by
Jay Sridhar
CORE ·
Mar. 13, 17 · Tutorial
Like (18)
Save
Tweet
Share
175.53K 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.

Popular on DZone

  • Artificial Intelligence in Drug Discovery
  • Three SQL Keywords in QuestDB for Finding Missing Data
  • Handling Automatic ID Generation in PostgreSQL With Node.js and Sequelize
  • Problems of Cloud Cost Management: A Socio-Technical Analysis

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: