You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java实现JSON转CSV时触发NullPointerException求助

Troubleshooting NullPointerException in JSON-to-CSV Conversion

Hey there! Let's work through that NullPointerException you're hitting when converting JSON to CSV with the json-to-csv library. Here are the most likely issues and fixes to try out:

Common Causes & Fixes

1. Your flatJson variable might be null

The JSONFlattener.parseJson() method will return null if it can't read or parse your JSON file properly. Passing a null flatJson to CSVWriter.getCSV() will immediately trigger a NullPointerException.

Fix: Add a validity check before calling CSV methods, and wrap the parsing step in error handling to catch exactly what's going wrong:

List<Map<String, String>> flatJson = null;
try {
    // Fix the file path here too (see next point!)
    flatJson = JSONFlattener.parseJson(new File("C:/Users/file/path/input.json"), "UTF-8");
} catch (IOException e) {
    e.printStackTrace();
    System.err.println("Couldn't read the JSON file: " + e.getMessage());
} catch (Exception e) {
    e.printStackTrace();
    System.err.println("Failed to parse JSON content: " + e.getMessage());
}

// Verify flatJson is valid before proceeding
if (flatJson == null) {
    System.err.println("JSON parsing failed - flatJson is null!");
    return;
}

// Now execute the CSV writer code safely
CSVWriter.writeToFile(CSVWriter.getCSV(flatJson, ";"), "C:/Users/file/path/output.csv");

2. Your file path has an error

Windows file paths shouldn't start with a leading slash. Your current path /C:/Users/... is invalid—remove the first slash to make it C:/Users/file/path/input.json. Alternatively, use escaped double backslashes like C:\\Users\\file\\path\\input.json.

An invalid path means the library can't locate your JSON file, so parseJson() returns null, leading directly to the NPE.

3. Your JSON file has syntax issues

If your input.json has invalid JSON (missing commas, unclosed quotes, mismatched brackets), the parser will fail silently and return null.

Fix: Use a JSON validator tool to check your file for syntax errors. Fix any issues (like missing brackets or quote mismatches) before trying to parse it again.

Quick Debugging Tip

To narrow down the root cause, print the flatJson variable right after parsing:

System.out.println("Parsed flatJson content: " + flatJson);

If it prints null, you know the problem lies in the parsing step (either path or JSON format). If it shows a populated list of maps, the issue might be within the CSVWriter methods themselves—but that's far less likely.

内容的提问来源于stack exchange,提问作者chris_evans

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:41:51