Attempting to transform a JSON file or string into a CSV format results in an unpopulated CSV file

So I have this task of converting a JSON file to a CSV file. I'm using the Google Sheets API to export the JSON file, but when I try to convert it, either with the file location or as a string, I always get a null pointer exception or an empty CSV file.

This is a sample of the JSON file:

{
  "range": "products!A1:E4",
  "majorDimension": "ROWS",
  "values": [
    [
      "product_name",
      "price"
    ],
    [
      "Rugrats - Bedtime Bash [VHS]",
      "36.95"
    ],
    [
      "Teenage Mutant Ninja Turtles II - The Secret of the Ooze [VHS]",
      "29.89"
    ],
    [
      "Teenage Mutant Ninja Turtles II - The Secret of the Ooze [VHS]",
      "29.89"
    ]
  ]
}

I am trying to use the following code for the conversion:

JSONObject output = new JSONObject(<String or file location that holds JSON file>);
File finalFile=new File(<Destination file path>);
JSONArray docs = output.getJSONArray("values");
String csv = CDL.toString(docs);
FileUtils.writeStringToFile(finalFile, csv);

Am I missing something in the code? Is there a different approach to handle this JSON data in Java?

Answer №1

Why not write directly from the Sheets API response (this example was extracted from the Java Sheet API quick-start)

public static void main(String... args) throws IOException, GeneralSecurityException {
    // Create a new authorized API client service.
    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    final String spreadsheetId = "<SHEET_ID>";
    final String range = "<SHEET_RANGE>";
    Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
            .setApplicationName(APPLICATION_NAME)
            .build();
    ValueRange response = service.spreadsheets().values()
            .get(spreadsheetId, range)
            .execute();
    List<List<Object>> values = response.getValues();
    if (values == null || values.isEmpty()) {
        System.out.println("No data found.");
    } else {
        /* Create a new writer */
        PrintWriter writer = new PrintWriter("data.csv");
        for (List<Object> list : values) {
            /* Building the string */
            StringBuilder str = new StringBuilder();
            str.append(list.get(0).toString() + ",");
            str.append(list.get(1).toString() + "\n");
            writer.write(str.toString());
        }
        /* Closing the writer */
        writer.close();
    }
}

In any case, if you are reading the JSON object correctly, the mechanism would be exactly the same.

Updated

If you want to read directly from JSON, consider using this example (using GSON):

public class SheetResponse {
    private String range;
    private String majorDimensions; 
    private List<List<Object>> values;
}

public static void main(String... args) throws IOException, GeneralSecurityException {
    // Create a new authorized API client service.
    var gson = new Gson();
    var reader = new JsonReader(new FileReader("test.json"));
    SheetResponse sR = gson.fromJson(reader, SheetResponse.class);
    PrintWriter writer = new PrintWriter("data.csv");
    for (List<Object> list : sR.values) {
        /* Building the string */
        StringBuilder str = new StringBuilder();
        str.append(list.get(0).toString() + ",");
        str.append(list.get(1).toString() + "\n");
        writer.write(str.toString());
    }
    /* Closing the writer */
    writer.close();
}
Updated for the general case
public static void main(String... args) throws IOException, GeneralSecurityException {
    // Create a new authorized API client service.
    var gson = new Gson();
    var reader = new JsonReader(new FileReader("test.json"));
    SheetResponse sR = gson.fromJson(reader, SheetResponse.class);
    PrintWriter writer = new PrintWriter("data.csv");

    for (int i = 0; i < sR.values.size(); i++) {
        var valueRow = sR.values.get(i);
        StringBuilder str = new StringBuilder();
        for (int j = 0; j < valueRow.size(); j++) {
            if (j == valueRow.size() - 1) {
                str.append(valueRow.get(j).toString() + "\n");
            } else {
                str.append(valueRow.get(j).toString() + ",");
            }
        }
        writer.write(str.toString());
    }
    /* Closing the writer */
    writer.close();
}
Documentation

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is the encoding logical when used in Python for JSON or YAML files?

I attempted to store this dictionary in a json or yaml file: d = {'name': 'María Gómez', 'message': '¡Es una caña atómica!'} with open(file, 'wt', encoding='iso8859-1') as file: json.dump( ...

Choosing Selenium Web Elements

Currently, I am working with Selenium and encountering an issue with one of the Xpaths in relation to creating a Gmail account. The problem lies with selecting the birth month option on the page. The Xpath I have provided below appears to be correct when e ...

Submit a JSON object containing just a single text string

Is there a way to post a JSON with just one line of text, for example: "Hello, I'm waiting for you" I attempted the following: { "":"Hello, I'm waiting for you" } Unfortunately, it did not work. Trying to post only the text also did not yield ...

The latest version of Spring MVC, 4.1.x, is encountering a "Not Acceptable" error while trying

After creating a Rest Service using Spring MVC4.1.X, I encountered an issue when attempting to return Json output to the browser. The error message displayed was: The resource identified by this request is only capable of generating responses with charact ...

Extract JSON data from a third-party website using JavaScript

I'm facing a challenge parsing JSON from an external website using JavaScript or jQuery for a Chrome extension. Specifically, I need to extract the number from an external URL with the JSON {"_visitor_alertsUnread":"0"} and assign that number to a var ...

Simple integration of JSP, JSON, and AJAX

I need help testing a simple login functionality using AJAX. Here's the code snippet: <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Login Test Page</title> <script src="../js/j ...

What is the best way to serialize a method within a model?

Is there a way to serialize the get_picture(self) method within this model? I am currently working on a social networking project and I need to serialize this method in order to obtain a JSON URL for the user's profile picture to be utilized in an And ...

Exploring the capabilities of JSONmodel by attempting to retrieve data from a server onto an iOS device

I've been working on integrating JSONmodel to retrieve data from my server to my iOS device. I have set up all the classes properly, but for some reason, it returns null after calling the URL. feed = [[Feeds alloc] initFromURLWithString:@"http://http ...

Creating a dynamic table using JQuery to display data from a JSON object with a flexible number of fields

Dear all, I must apologize for any messy coding errors as this is my first attempt at something like this and I am learning on the go. I am currently working on using JQuery's $.each() method to iterate through a JSON object retrieved via an Ajax cal ...

The Jetty server is unable to provide JSON responses

Whenever I use the command mvn jetty:run to initiate my server, it fails to return JSON formatted strings. Instead, it only returns raw strings or "null" for all objects. In the code snippet for my endpoint, you can observe that there is no variation in r ...

trouble encountered while parsing JSON information using JavaScript

[ [ { "Id": 1234, "PersonId": 1, "Message": "hiii", "Image": "5_201309091104109.jpg", "Likes": 7, "Status": 1, "OtherId": 3, "Friends": 0 } ], [ { "Id": 201309091100159, "PersonI ...

What is the most efficient way to locate the next occurrence of a sub-buffer within a larger buffer, especially when you have a specified minimum distance to search

Summary: Although there are existing CSV file reading libraries for Node.js, I decided to create my own function to maximize optimization based on the specific properties of my CSV format. The file contains a variable entry-count-per line structure, which ...

Why does my JSON parser consume significantly more memory when utilizing the Streaming API?

My current code is parsing the whole file using jsonparse: ConcurrentHashMap<String, ValueClass<V>> space = new ConcurrentHashMap<String, ValueClass<V>> (); Map<String, ValueClass<V>> map = mapper.readValue(new FileRead ...

Traverse a collection of nested objects containing arrays as their values

Consider the following object: { "apples": [ "one", "two" ], "oranges": [ "three", "four" ] } If I want to find the value four within this object, how can I do so efficiently? Would a loop work, like the one shown below? for (var ...

Trigger a PHP script to execute whenever a user updates a row in a MySQL/WordPress database

I am currently in the process of developing a small web application that will retrieve data from a specific row in a database on a WordPress based website. This data will be used to populate an announcers section for a radio station on another website. Th ...

Leveraging OPENJSON in SQL Server Query

I'm facing a challenge with extracting information from a JSON array stored in an SQL Server database. While I understand that the OPENJSON function needs to be used for this task, most examples I've come across focus on declaring a single JSON a ...

`How can I effectively integrate react-i18next with the Semantic UI label element?`

Currently, I am working with Semantic UI along with the integration of [react-i18next][2]. My goal is to enable translation for label strings, but these labels include HTML tags, such as span. Unfortunately, the system only allows hardcoded or variable s ...

Verify the occurrence of a search result and if it appears more than once, only show it once using JavaScript

Hello all. Currently, I am developing an online users script using NodeJS and SocketIO. The functionality works fine, however, I am encountering an issue where if a user connects from multiple browsers, windows, or devices, it displays duplicate results li ...

How can I troubleshoot the RegistryBuilder problem encountered during Junit testing with Maven?

I recently created a test in Juni and added it to my Maven project. However, when I try to build the project, I encounter the following error: java.lang.NoClassDefFoundError: org/apache/http/config/RegistryBuilder at org.openqa.selenium.remote.int ...

Efficient Local Database with Javascript

When storing a substantial amount of data, such as a big hashmap in JavaScript, what would be the optimal format for quick retrieval while also supporting Unicode? Would XML or JSON be better suited for this purpose? ...