【问题标题】:Why is my code not correctly converting JSON to CSV?为什么我的代码没有正确地将 JSON 转换为 CSV?
【发布时间】:2016-12-16 12:12:44
【问题描述】:

我想将此 JSON 转换为 CSV:

{"field1": 11,"field3": 13},
{"field1": 21,"field2": 22,"field3": 23},
{"field1": 31,"field2": 32,"field3": 33,"field4": 34}  

为此,我使用以下代码:

  String jsonString1 = "{\"infile\": [{\"field1\": 11,\"field3\": 13},{\"field1\": 21,\"field2\": 22,\"field3\": 23},{\"field1\": 31,\"field2\": 32,\"field3\": 33,\"field4\": 34}]}";

     try
     {   
         output = new JSONObject(jsonString1);
         String destination = "tmp/json2csv.csv";
         JSONArray docs = output.getJSONArray("infile");

         File file = new File(destination);
         String csv = CDL.toString(docs);
         FileUtils.writeStringToFile(file, csv);
    }
    catch (JSONException e) {

    }

我希望 CSV 输出与此表等效:

field1  field2  field3  field4
11              13  
21       22     23  
31       32     33       34       

但目前它正在输出与此表等效的 CSV:

field1  field2  field3  field4
13              13  
21              23  
31              33  

为什么这段代码没有返回我期望的结果?

【问题讨论】:

  • 请给我们 CDL.toString() 方法/类和 JSONObject 类的代码。目前您给我们的代码并没有向我们展示任何实际的实现细节,所以回答这个问题是不可能的。
  • 向我们展示有趣的代码(可能是 CDL.toString)。否则我们无法帮助您。

标签: java json csv


【解决方案1】:

假设您使用的是org.json.CDL,那么您想尝试重载方法String toString(JSONArray names, JSONArray ja)

try
{
    JSONObject output = new JSONObject(jsonString1);
    JSONArray docs = output.getJSONArray("infile");
    JSONArray names = new JSONArray("['field1', 'field2', 'field3', 'field4']");
    String header = CDL.rowToString(names);
    String csv = header + CDL.toString(names, docs);

    String destination = "tmp/json2csv.csv";
    File file = new File(destination);
    FileUtils.writeStringToFile(file, csv);
}
catch (Exception e) {
    e.printStackTrace();
}

【讨论】:

  • CDL.toString() 返回“null”
  • 您可能需要检查您的 CDL 版本的源代码。最有可能在 2 年多之后发生一些变化
猜你喜欢
  • 1970-01-01
  • 2021-07-27
  • 1970-01-01
  • 2021-02-23
  • 2014-10-06
  • 2022-01-06
  • 1970-01-01
  • 2019-03-12
  • 1970-01-01
相关资源
最近更新 更多