为什么我的代码没有正确地将JSON转换为CSV?

时间:2016-12-16 12:12:44

标签: java json csv

我想将此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  

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

1 个答案:

答案 0 :(得分:0)

假设您使用的是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();
}