如何解决Ballerina,使用来自 REST-API 的 Json 响应
我的教授要我写一个关于如何部署 Ballerina 服务的小教程。所以我正在努力学习它。我使用的是 1.2 版,我对污点检查和变量类型的概念有点不知所措...
我正在尝试编写一个带有端点的最小 REST 服务,该端点从另一个 api 请求 json 数据,然后使用该 JSON 来做事。
目前有效的是:
service tutorial on new http:Listener(9090) {
// Resource functions are invoked with the HTTP caller and the incoming request as arguments.
resource function getName(http:Caller caller,http:Request req) {
http:Client clientEP = new("https://api.scryfall.com/");
var resp = clientEP->get("/cards/random");
if (resp is http:Response) {
var payload = resp.getJsonPayload();
if (payload is json) {
var result = caller->respond(<@untainted>(payload));
} else {
log:printError("");
}
} else {
log:printError("");
}
}
使用从 https://api.scryfall.com/cards/random 返回的 JSON 进行响应
但是现在可以说,我想从该 JSON 访问单个值。例如。 “名称”。 如果我尝试像这样访问它:payload["name"]
我得到:无效操作:类型“json”不支持索引
我刚刚发现,如果我先像这样创建地图,它会起作用:
map mp =
如果我然后访问 mp["name"] 它工作。但为什么?如果您仍然需要创建地图然后投射有效负载,那么 json 类型有什么用?我将如何访问 json 中的 json?例如 mp["data"][0]... 无效操作:类型 'json' 不支持再次索引...
而且我仍在尝试理解污点检查的概念.... 在检查内容后,我是否只是将所有被污染的内容投射到 ? 有时我真的不明白文档试图告诉我什么......
解决方法
我建议您使用 Ballerina Swan Lake 版本。 Swan Lake 版本包含对各种语言功能的增强。这是涵盖您的用例的示例代码。您可以在 https://ballerina.io/
下载 Swan Lake Alpha2import ballerina/io;
import ballerina/http;
service tutorial on new http:Listener(9090) {
resource function get payload() returns json|error {
http:Client clientEP = check new ("https://api.scryfall.com/");
json payload = <json> check clientEP -> get("/cards/random",targetType = json);
// Processing the json payload
// Here the type of the `payload.name` expression is json | error
// You can eliminate with check: it returns from this resource with this error
json nameField = check payload.name;
io:println(nameField);
// You can traverse the json tree as follows
json standardLegality = check payload.legalities.standard;
io:println(standardLegality);
// colors is an array
// The cast is necessary because `check payload.colors` gives you a json
json colors = <json[]> check payload.colors;
io:println(colors);
// Responding with the complete payload recived from api.scryfall.com
return payload;
}
}
污点分析可帮助您编写没有安全漏洞的代码。但是,我们在 Swan Lake 版本中禁用了污点分析。如果要启用它,可以将选项 --taint-check
与 bal build
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。