获取JSONObject作为数组,以帮助将其转换为CSV

时间:2017-03-03 09:37:59

标签: java json csv

我想要的是什么:

在csv文件中获取JSONObject的值。

我想这个问题有点接近我想要的,但我无法从here得到答案。

我有什么:

以下json:

{
"day_entries": [
    {
        "project_id": "5198193",
        "project": "14775",
        "user_id": 508343,
        "spent_at": "2016-01-27",
        "task_id": "2892243",
        "task": "Backend Programming",
        "client": "Apple",
        "id": 420923769,
        "notes": "",
        "started_at": "12:00pm",
        "ended_at": "2:00pm",
        "created_at": "2016-01-27T21:30:00Z",
        "updated_at": "2016-01-27T21:30:00Z",
        "hours_without_timer": 2,
        "hours": 2
    }
],
"for_day": "2016-01-27"
}

我为此编写的代码是:

  /**
 * Converts the day_entries JSONObject to csv string values and returns as ArrayList
 * @param dayEntries
 * @return null if there is any error parsing TimeSheet JSON response
 */
public static ArrayList<String> writeTimeSheetJSONCDR(JSONArray dayEntries) {
    try {
        ArrayList<String> cdrRows = new ArrayList<String>();
        StringBuilder cdrEntry = new StringBuilder();
        for (int i = 0; i < dayEntries.length(); i++) {
            JSONObject jsonDayEntry = (JSONObject) dayEntries.get(i);

            cdrEntry.append(jsonDayEntry.get("for_day")).append(",");
            cdrEntry.append(jsonDayEntry.get("project_id"));
            cdrEntry.append(",");
            cdrEntry.append(jsonDayEntry.get("project"));
            cdrEntry.append(",");
            cdrEntry.append(jsonDayEntry.get("user_id"));
            cdrEntry.append(",");
            cdrEntry.append(jsonDayEntry.get("spent_at"));
            cdrEntry.append(",");
            cdrEntry.append(jsonDayEntry.get("task_id"));
            cdrEntry.append(",");
            cdrEntry.append(jsonDayEntry.get("task"));
            cdrEntry.append(",");
            cdrEntry.append(jsonDayEntry.get("client"));
            cdrEntry.append(",");
            cdrEntry.append(jsonDayEntry.get("id"));
            cdrEntry.append(",");
            cdrEntry.append(jsonDayEntry.get("notes"));
            cdrEntry.append(",");
            cdrEntry.append(jsonDayEntry.get("started_at"));
            cdrEntry.append(",");
            cdrEntry.append(jsonDayEntry.get("ended_at"));
            cdrEntry.append(",");
            cdrEntry.append(jsonDayEntry.get("created_at"));
            cdrEntry.append(",");
            cdrEntry.append(jsonDayEntry.get("updated_at"));
            cdrEntry.append(",");
            cdrEntry.append(jsonDayEntry.get("hours_without_timer"));
            cdrEntry.append(",");
            cdrEntry.append(jsonDayEntry.get("hours"));
            cdrRows.add(cdrEntry.toString());
        }
        System.out.println("CDREntry: " + cdrEntry.toString());
        return cdrRows;
    } catch (Exception exp) {
        System.err.println("Error parsing json" + exp);
        return null;
    }
}

我的问题:

有没有办法让后续的子节点作为数组而不单独指定键,我不必像我一样提到所有的键?

3 个答案:

答案 0 :(得分:1)

我强烈建议您使用GSON project(或其Maven version)轻松地将JSON对象用于Java对象。所以现在,您必须创建Java类来封装JSON对象:

public class Entry
{
   private DayEntry[] day_entries;
   private String for_day;

   //getters and setters
}

public class DayEntry {
   private String project_id;
   private String project;
   private String user_id;
   private String spent_at;
   private String task_id;
   private String task;
   private String client;
   private String id";
   private String notes;
   private String started_at;
   private String ended_at;
   private String created_at;
   private String updated_at;
   private int hours_without_timer;
   private int hours;

   //getters and setters
}

然后,要转换JSON对象(包含在String对象中),请执行以下操作:

Gson gson = new GsonBuilder().setPrettyPrinting().create();
gson.fromJson(jsonString, Entry.class);

一旦你已经填充了Entry对象,就可以很容易地添加到CSV文件中。我使用opencsv库来做到这一点!

希望它可以帮到你!

答案 1 :(得分:1)

您可以执行以下代码:

public static ArrayList<String> writeTimeSheetJSONCDR(JSONArray dayEntries) {
        try {
            ArrayList<String> cdrRows = new ArrayList<String>();
            StringBuilder cdrEntry = new StringBuilder();
            for (int i = 0; i < dayEntries.length(); i++) {
                JSONObject jsonDayEntry = (JSONObject) dayEntries.get(i);


                Iterator iterator = jsonDayEntry.keys();

                while (iterator.hasNext()){
                    String key =(String) iterator.next();
                    cdrEntry.append(jsonDayEntry.get(key)).append(",");
                }

                cdrRows.add(cdrEntry.toString());
            }
            System.out.println("CDREntry: " + cdrEntry.toString());
            return cdrRows;
        } catch (Exception exp) {
            System.err.println("Error parsing json" + exp);
            return null;
        }
    }

答案 2 :(得分:0)

我会使用GSON库。首先使用必要的字段创建一个java对象,如:

public class DayEntriesJson {
    @SerializedName("project_id")
    private Long projectId;

    @SerializedName("project")
    private Long project;

    and so
    on
}

将json解析为对象:

new Gson().fromJson(reader, DayEntriesJson .class);

最后如果你想很好地打印字符串类,只需在DayEntriesJson和其他json类中覆盖toString。