我正在嘗試從用 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", "[email protected]"),
entry("emotion", "happy")
);
var writer = new PrintWriter(response.getWriter());
writer.write(returnJSON);
}
這樣做的最終目標是向ReturnJSON函式(部署為特定 URL 的云函式)發送 HTTP 請求,當我使用 JavaScript 獲取它時,該函式回傳 JSON:
fetch("https://example.com/return-json", { method: "GET" })
.then(response => response.json())
.then(data => console.log(data));
uj5u.com熱心網友回復:
JSON 只是一個字串,但在這種情況下,最好使用 Java 庫構建 JSON。有幾個選擇
https://github.com/stleary/JSON-java
http://json-lib.sourceforge.net/
uj5u.com熱心網友回復:
您必須將 json 撰寫為字串并在回應中添加內容型別,就像這樣
response.setContentType("application/json");
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/394927.html
