1

What I want:

Get the values of a JSONObject in a csv file.

I guess this question is somewhat near to what i want, but I couldn't get the answer from here.

What I have:

The following 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"
}

The code I have written for this is:

  /**
 * 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;
    }
}

My Question:

Is there a way to get the subsequent childs as array without specifying the keys individually and I don't have to mention all the keys like I have done?

Community
  • 1
  • 1
shabby
  • 3,002
  • 3
  • 39
  • 59
  • I think you could find some stuff in this article http://stackoverflow.com/questions/5015844/parsing-json-object-in-java. There is a solution for parsing JsonObjects into an array. – Lukas Hieronimus Adler Mar 03 '17 at 09:52

3 Answers3

1

I highly recommend you to use GSON project (or its Maven version) to easily use a JSON object into a Java object. So now, you must to create the Java class to encapsulate the JSON object:

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

   //getters and setters
}

and

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
}

Then, to convert JSON object (contained in String object), do something like:

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

Once you have the Entryobject already populated, it will be fairly easy to add to CSV file. I use opencsv library to do so!

Hope it helps you!

Gui
  • 72
  • 9
Loic P.
  • 691
  • 6
  • 18
1

You can do this like below code:

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;
        }
    }
Chetan Joshi
  • 5,582
  • 4
  • 30
  • 43
0

I would use the GSON library to that. First create a java object with the necessary fields like:

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

    @SerializedName("project")
    private Long project;

    and so
    on
}

parse json to object like:

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

and finally if you want to nicely print to string the class, just overwrite toString in DayEntriesJson and other json classes.

pezetem
  • 2,503
  • 2
  • 20
  • 38