【问题标题】:How do I return JSON from a Google Cloud Function written in Java?如何从用 Java 编写的 Google Cloud Function 返回 JSON?
【发布时间】:2022-01-26 04:56:46
【问题描述】:

我正在尝试从用 Java 编写的 Google Cloud Function 返回 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 函数(部署为某个 URL 的云函数)发送 HTTP 请求,当我使用 JavaScript 获取它时返回 JSON: p>

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

【问题讨论】:

    标签: java json google-cloud-functions httpresponse


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

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

      response.setContentType("application/json");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-15
        • 2019-02-14
        • 2020-02-11
        • 1970-01-01
        • 2017-08-04
        • 2020-12-17
        • 2017-12-17
        • 2021-12-28
        相关资源
        最近更新 更多