如何从用 Java 编写的 Google 云函数中 return JSON?

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

我正在尝试从用 Java 编写的 Google 云函数中 return 格式的 JSON 数据。我有一个来自 GoogleCloudPlatform/java-doc-samples (https://github.com/GoogleCloudPlatform/java-docs-samples/blob/main/functions/http/http-method/src/main/java/functions/HttpMethod.java) 的示例,它向我展示了如何处理不同类型的 HTTP 方法,但它没有展示如何在响应中编写 JSON。

我想做的事情如下:

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);
  }

这样做的最终目标是向 ReturnJSON 函数发送 HTTP 请求(作为云函数部署在某个 URL) 当我使用 Java 脚本获取它时 returns JSON:

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

JSON 只是一个字符串,但在这种情况下,您最好使用 Java 库构建 JSON。选项很少

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

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

您必须将 json 写成字符串并在响应中添加内容类型,就像那样

response.setContentType("application/json");