杰瑞科技汇

Java如何实现JSON转CSV?

Of course! Converting JSON to CSV in Java is a common task. There are several ways to do it, ranging from manual parsing for simple cases to using robust libraries for complex scenarios.

Java如何实现JSON转CSV?-图1
(图片来源网络,侵删)

Here’s a comprehensive guide covering the most popular and effective methods.

Summary of Methods

Method Pros Cons Best For
Jackson Library Highly recommended. Powerful, fast, handles complex nested objects/arrays. Requires an external dependency. Adds a library to your project. Most production applications. The standard, most robust solution.
Gson Library Very similar to Jackson. Excellent performance. Great alternative if you already use Gson. Adds a library to your project. Projects already using Gson or when you prefer its API.
Manual Parsing (No Libraries) No external dependencies. Good for learning or very simple, predictable JSON. Brittle, error-prone, doesn't handle nested objects/arrays well. Simple scripts or quick-and-dirty conversions where you can't add dependencies.

Method 1: Using the Jackson Library (Recommended)

Jackson is the de-facto standard for JSON processing in Java. It's fast, feature-rich, and can handle complex data structures.

Step 1: Add Jackson Dependency

You need to add the Jackson Databind library to your project. If you're using a build tool like Maven or Gradle, add the following dependency.

Maven (pom.xml):

Java如何实现JSON转CSV?-图2
(图片来源网络,侵删)
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version> <!-- Use the latest version -->
</dependency>

Gradle (build.gradle):

implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.2' // Use the latest version

Step 2: Write the Java Code

The key challenge is handling JSON objects and arrays. We'll create a generic converter that works for a list of JSON objects, where each object represents a row in the CSV.

Example JSON (data.json):

[
  {
    "id": 1,
    "firstName": "John",
    "lastName": "Doe",
    "email": "john.doe@example.com",
    "age": 30
  },
  {
    "id": 2,
    "firstName": "Jane",
    "lastName": "Smith",
    "email": "jane.smith@example.com",
    "age": 28
  },
  {
    "id": 3,
    "firstName": "Peter",
    "lastName": "Jones",
    "email": "peter.jones@example.com",
    "age": 45
  }
]

Java Code (JsonToCsvConverter.java): This code reads the JSON, extracts all headers, and then iterates through each object to write a row.

Java如何实现JSON转CSV?-图3
(图片来源网络,侵删)
import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class JsonToCsvConverter {
    public static void main(String[] args) {
        // Input JSON file
        File jsonFile = new File("data.json");
        // Output CSV file
        File csvFile = new File("output.csv");
        try {
            // 1. Create a CsvMapper
            CsvMapper csvMapper = new CsvMapper();
            // 2. Define the CSV schema
            // This schema is built from the first object in the list
            // It will be used for all subsequent rows
            CsvSchema schema = csvMapper.schemaFor(Object.class).withHeader();
            // 3. Read JSON into a list of objects
            ObjectMapper objectMapper = new ObjectMapper();
            MappingIterator<Object> mappingIterator = objectMapper.readerFor(Object.class).readValues(jsonFile);
            // 4. Write the list of objects to a CSV file
            // ObjectWriter handles the mapping from objects to CSV format using the schema
            ObjectWriter writer = csvMapper.writer(schema);
            writer.writeValues(csvFile).writeAll(mappingIterator);
            System.out.println("Successfully converted JSON to CSV at: " + csvFile.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How it Works:

  1. CsvMapper: A specialized ObjectMapper for handling CSV files.
  2. schemaFor(Object.class): Tells Jackson to inspect the objects to determine the columns (CSV headers).
  3. .withHeader(): Ensures the first row of the CSV file contains the column names (e.g., id, firstName, lastName).
  4. objectMapper.readerFor(...): Creates a reader to parse the JSON file.
  5. mappingIterator: This is an efficient way to stream the JSON objects one by one, which is great for large files.
  6. csvMapper.writer(schema): Creates a writer configured with the schema we defined.
  7. writeValues(csvFile).writeAll(...): This is the magic part. It opens the output file, writes the header (based on the schema), and then iterates through all the JSON objects, writing each one as a new row in the CSV.

Output (output.csv):

id,firstName,lastName,email,age
1,John,Doe,john.doe@example.com,30
2,Jane,Smith,jane.smith@example.com,28
3,Peter,Jones,peter.jones@example.com,45

Method 2: Using the Gson Library

Gson is another excellent library from Google. The approach is very similar to Jackson.

Step 1: Add Gson Dependency

Maven (pom.xml):

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version> <!-- Use the latest version -->
</dependency>

Gradle (build.gradle):

implementation 'com.google.code.gson:gson:2.10.1' // Use the latest version

Step 2: Write the Java Code

Gson doesn't have a built-in CSV writer, so we'll use a standard JavaWriter and manually handle the CSV formatting (e.g., escaping quotes and commas).

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
public class JsonToCsvConverterGson {
    public static void main(String[] args) {
        String jsonString = "[\n" +
                "  {\"id\": 1, \"firstName\": \"John\", \"lastName\": \"Doe\", \"email\": \"john.doe@example.com\"},\n" +
                "  {\"id\": 2, \"firstName\": \"Jane\", \"lastName\": \"Smith\", \"email\": \"jane.smith@example.com\"},\n" +
                "  {\"id\": 3, \"firstName\": \"Peter\", \"lastName\": \"Jones\", \"email\": \"peter.jones@example.com\"}\n" +
                "]";
        String csvFile = "output_gson.csv";
        try (Writer writer = new FileWriter(csvFile)) {
            JsonElement jsonElement = JsonParser.parseString(jsonString);
            JsonArray jsonArray = jsonElement.getAsJsonArray();
            if (jsonArray == null || jsonArray.isEmpty()) {
                System.out.println("No data to convert.");
                return;
            }
            // 1. Get headers from the first object
            JsonObject firstObject = jsonArray.get(0).getAsJsonObject();
            List<String> headers = new ArrayList<>();
            for (String key : firstObject.keySet()) {
                headers.add(key);
            }
            // 2. Write CSV header
            writeLine(writer, headers);
            // 3. Write data rows
            for (JsonElement element : jsonArray) {
                JsonObject jsonObject = element.getAsJsonObject();
                List<String> values = new ArrayList<>();
                for (String header : headers) {
                    // Handle potential null values
                    JsonElement value = jsonObject.get(header);
                    values.add(value != null ? value.getAsString() : "");
                }
                writeLine(writer, values);
            }
            System.out.println("Successfully converted JSON to CSV using Gson at: " + csvFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // Helper method to write a line to the CSV, handling proper escaping
    private static void writeLine(Writer writer, List<String> values) throws IOException {
        boolean first = true;
        for (String value : values) {
            if (!first) {
                writer.append(',');
            }
            // Escape quotes and wrap in quotes if the value contains a comma, quote, or newline
            if (value.contains(",") || value.contains("\"") || value.contains("\n")) {
                writer.append('"').append(value.replace("\"", "\"\"")).append('"');
            } else {
                writer.append(value);
            }
            first = false;
        }
        writer.append('\n');
    }
}

Method 3: Manual Parsing (No Libraries)

This method is for very simple, predictable JSON where you know the exact structure beforehand. It's not recommended for production code.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class JsonToCsvManual {
    public static void main(String[] args) {
        String jsonFile = "data.json";
        String csvFile = "output_manual.csv";
        try (BufferedReader reader = new BufferedReader(new FileReader(jsonFile));
             FileWriter writer = new FileWriter(csvFile)) {
            // This is a very naive approach. It will break easily.
            String line;
            StringBuilder jsonString = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                jsonString.append(line.trim());
            }
            // Remove the square brackets and split by "},{"
            String content = jsonString.toString().replace("[", "").replace("]", "");
            String[] objects = content.split("},");
            // Manually extract headers (this is fragile)
            writer.append("id,firstName,lastName,email,age\n");
            for (String obj : objects) {
                // Fix the last object if it doesn't have a trailing '}'
                if (!obj.endsWith("}")) {
                    obj += "}";
                }
                // Find and extract values by key
                String id = getValue(obj, "\"id\":");
                String firstName = getValue(obj, "\"firstName\":");
                String lastName = getValue(obj, "\"lastName\":");
                String email = getValue(obj, "\"email\":");
                String age = getValue(obj, "\"age\":");
                writer.append(id).append(",")
                      .append(firstName).append(",")
                      .append(lastName).append(",")
                      .append(email).append(",")
                      .append(age).append("\n");
            }
            System.out.println("Successfully converted JSON to CSV manually at: " + csvFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // Helper to find a value by its key. Very brittle!
    private static String getValue(String json, String key) {
        int startIndex = json.indexOf(key) + key.length();
        if (startIndex < key.length()) return ""; // Key not found
        int endIndex = json.indexOf(",", startIndex);
        if (endIndex == -1) endIndex = json.indexOf("}", startIndex);
        String value = json.substring(startIndex, endIndex).trim();
        // Remove quotes if present
        if (value.startsWith("\"") && value.endsWith("\"")) {
            value = value.substring(1, value.length() - 1);
        }
        return value;
    }
}

Conclusion

For any serious application, use the Jackson library. It's the most robust, flexible, and efficient solution. The Gson library is a close second and is an excellent choice if your project is already built around it. Avoid manual parsing unless you have a very simple, one-off task and cannot add any external dependencies.

分享:
扫描分享到社交APP
上一篇
下一篇