我正试图从用Java编写的谷歌云函数返回JSON格式的数据。我有一个GoogleCloudPlatform/java文档示例(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时返回JSON:
fetch("https://example.com/return-json", { method: "GET" })
.then(response => response.json())
.then(data => console.log(data));
您必须将json写为字符串,并在响应中添加内容类型,如
response.setContentType("application/json");
JSON只是一个字符串,但在这种情况下,最好使用Java库构建JSON。的选项很少
https://github.com/stleary/JSON-java
http://json-lib.sourceforge.net/