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

Time:12-28

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", "[email protected]"),
        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));

CodePudding user response:

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/

CodePudding user response:

You have to write your json as a string and to add the content type in the response, like that

response.setContentType("application/json");
  • Related