Search code examples
javajsongoogle-cloud-functionshttpresponse

How do I return JSON from a Google Cloud Function written in Java?


I am trying to return data in JSON format from a Google Cloud Function written in Java. I have an example from GoogleCloudPlatform/java-doc-samples (https://github.com/GoogleCloudPlatform/java-docs-samples/blob/main/functions/http/http-method/src/main/java/functions/HttpMethod.java) that shows me how to handle different types of HTTP methods, but it doesn't show how to write JSON in the response.

What I'd like to do would be something like the following:

import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import static java.util.Map.entry;

public class ReturnJSON implements HttpFunction {

  @Override
  public void service(HttpRequest request, HttpResponse response)
      throws IOException {

    Map<String, String> returnJSON = Map.ofEntries(
        entry("name", "Test User"),
        entry("email", "test_user@example.com"),
        entry("emotion", "happy")
    );

    var writer = new PrintWriter(response.getWriter());
    writer.write(returnJSON);
  }

The end goal of this would be to send an HTTP request to the ReturnJSON function (deployed as a cloud function at a certain URL) that returns JSON when I use JavaScript to fetch it:

fetch("https://example.com/return-json", { method: "GET" })
  .then(response => response.json())
  .then(data => console.log(data));

Solution

  • JSON is just a string but you are better off building JSON using a Java library in this case. there are few options

    https://github.com/stleary/JSON-java

    http://json-lib.sourceforge.net/