简体   繁体   English

JSON转换为CSV错误-java.lang.NullPointerException

[英]JSON to CSV error - java.lang.NullPointerException

I am trying to convert a JSON file to a CSV file using Java. 我正在尝试使用Java将JSON文件转换为CSV文件。 I am newbie. 我是新手。

I am following https://github.com/Arkni/json-to-csv tutorial. 我正在关注https://github.com/Arkni/json-to-csv教程。

I'm getting a NullPointerException. 我收到了NullPointerException。

Any help is appreciated. 任何帮助表示赞赏。

My code: 我的代码:

test.java test.java

List<Map<String, String>> flatJson;
flatJson = JSONFlattener.parseJson(new File("/C:/Users/file/path/input.json"), "UTF-8");
!!---CSVWriter.writeToFile(CSVWriter.getCSV(flatJson, ";"), "/C:/Users/file/path/output.csv");--!!

Error_line: CSVWriter.writeToFile(CSVWriter.getCSV(flatJson, ";"), "/C:/Users/file/path/output.csv"); 错误行: CSVWriter.writeToFile(CSVWriter.getCSV(flatJson, ";"), "/C:/Users/file/path/output.csv");

CSVWriter.java: CSVWriter.java:

 private static final Logger LOGGER = Logger.getLogger(CSVWriter.class);

    public static String getCSV(List<Map<String, String>> flatJson) {
        return getCSV(flatJson, ",");
    }

    public static String getCSV(List<Map<String, String>> flatJson, String separator) {
       !!!-- ***Set<String> headers = collectHeaders(flatJson);***---!!!!
        String csvString = StringUtils.join(headers.toArray(), separator) + "\n";

     !!!!---   ***for (Map<String, String> map : flatJson) {***---!!!
            csvString = csvString + getSeperatedColumns(headers, map, separator) + "\n";
        }

        return csvString;
    }

    public static void writeToFile(String csvString, String fileName) {
        try {
            FileUtils.write(new File(fileName), csvString);
        } catch (IOException e) {
            LOGGER.error("CSVWriter#writeToFile(csvString, fileName) IOException: ", e);
        }
    }

    private static String getSeperatedColumns(Set<String> headers, Map<String, String> map, String separator) {
        List<String> items = new ArrayList<String>();
        for (String header : headers) {
            String value = map.get(header) == null ? "" : map.get(header).replaceAll("[\\,\\;\\r\\n\\t\\s]+", " "); 
            items.add(value);
        }

        return StringUtils.join(items.toArray(), separator);
    }

    private static Set<String> collectHeaders(List<Map<String, String>> flatJson) {
        Set<String> headers = new LinkedHashSet<String>();

        for (Map<String, String> map : flatJson) {
            headers.addAll(map.keySet());
        }

        return headers;
    }

Error_line: 错误行:

Set<String> headers = collectHeaders(flatJson);

for (Map<String, String> map : flatJson) {

ERROR: 错误:

Exception in thread "main" java.lang.NullPointerException
    at test2.CSVWriter.collectHeaders(CSVWriter.java:134)
    at test2.CSVWriter.getCSV(CSVWriter.java:49)
    at test2.test2.main(test.java:20)

I suspect the JSON file you are trying to read either does not exist, there is some other I/O error reading it in or it contains malformed JSON. 我怀疑您尝试读取的JSON文件不存在,在读取该文件时存在其他I / O错误,或者该文件包含格式错误的JSON。

Unfortunately, the error-handling in the parseJson method you are using leaves a lot to be desired. 不幸的是,您正在使用的parseJson方法中的错误处理还有很多不足之处。 Here's the entire text of it ( source ): 这是它的全部文本( source ):

public static List<Map<String, String>> parseJson(URI uri, String encoding) {
    List<Map<String, String>> flatJson = null;
    String json = "";

    try {
        json = IOUtils.toString(uri, encoding);
        flatJson = parseJson(json);
    } catch (IOException e) {
        LOGGER.error("JsonFlattener#ParseJson(uri, encoding) IOException: ", e);
    } catch (Exception ex) {
        LOGGER.error("JsonFlattener#ParseJson(uri, encoding) Exception: ", ex);
    }

    return flatJson;
}

If an exception is thrown reading in the file or parsing the JSON, it writes a message to LOGGER (which is a Log4J logger) and then returns null . 如果在读取文件或解析JSON时引发异常,则它将消息写入LOGGER (Log4J记录器),然后返回null As you describe yourself as a newbie, I'm going to guess Log4J isn't quite set up correctly (you may have seen a message about log4j.properties or log4j.xml file not being found), so the logging isn't working, the error message gets lost and you don't find out what the problem is. 当您形容自己是新手时,我猜想Log4J的设置不正确(您可能已经看到有关log4j.properties或log4j.xml文件的消息),因此日志记录无法正常工作,错误消息会丢失,您无法找出问题所在。

As a first step I would simply avoid calling this method. 第一步,我只是避免调用此方法。 Instead of writing 而不是写作

List<Map<String, String>> flatJson;
flatJson = JSONFlattener.parseJson(new File("/C:/Users/file/path/input.json"), "UTF-8");
CSVWriter.writeToFile(CSVWriter.getCSV(flatJson, ";"), "/C:/Users/file/path/output.csv");

write the following instead: 改写以下内容:

List<Map<String, String>> flatJson;
String json = IOUtils.toString(new File("/C:/Users/file/path/input.json"), "UTF-8");
flatJson = JSONFlattener.parseJson(json);
CSVWriter.writeToFile(CSVWriter.getCSV(flatJson, ";"), "/C:/Users/file/path/output.csv");

You may need to add a line import org.apache.commons.io.IOUtils; 您可能需要添加一行import org.apache.commons.io.IOUtils; and handle some more exceptions, but those exceptions should hopefully tell you what is going wrong. 并处理其他一些异常,但是这些异常应该可以告诉您出了什么问题。

However, having looked further at the source code of this library, this may not help too much. 但是,进一步研究该库的源代码后,这可能并没有太大帮助。 There are other places where it simply catches Exception , writes a generic message to the log and returns null . 在其他地方,它仅捕获Exception ,将通用消息写入日志并返回null You may have to look elsewhere for a better alternative library. 您可能需要在其他地方寻找更好的替代库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM