type-conversion - 如何将带有保留关键字的 JSON 有效负载转换为名称以在 Ballerina 中记录
问题描述
我正在开发一个 Ballerina 服务,该服务接收事件并使用该convert
函数将 JSON 有效负载转换为记录。该事件包含一个名称type
为 Ballerina 中保留关键字的字段。我无法更改事件的有效负载。string type;
以下是一个简化的示例代码,由于记录中的原因,无法编译Event
。更改type
为Type
或eventType
允许编译,但执行会引发错误,因为 JSON 有效负载的字段名称与记录的字段名称不匹配。
import ballerina/http;
import ballerina/io;
type Event record {
string id;
string type;
string time;
};
@http:ServiceConfig { basePath: "/" }
service eventservice on new http:Listener(8080) {
@http:ResourceConfig { methods: ["POST"], path: "/" }
resource function handleEvent(http:Caller caller, http:Request request) {
json|error payload = request.getJsonPayload();
Event|error event = Event.convert(payload);
io:println(event);
http:Response response = new;
_ = caller -> respond(response);
}
}
这是一个curl
命令,它发送一个带有 JSON 有效负载和一个名为 的字段的示例事件type
。
curl -X POST localhost:8080 -H "content-type: application/json" -d "{\"id\":\"1\",\"type\":\"newItem\",\"time\":\"now\"}"
我通读了 Ballerinas API 文档,并没有发现关于这个主题的任何内容。
来自 Java 世界,我希望像这样的记录字段上的注释:
type Event record {
string id;
@JsonProperty("type")
string eventType;
string time;
};
有没有人遇到过这个问题,甚至更好地找到了解决方案?
解决方案
您可以按如下方式定义事件:
type Event record {
string id;
string 'type;
string time;
};
The'
用于转义 Ballerina 中的关键字。访问它时,您也可以将其用作event.'type
在这里您可以找到一个示例用法。
推荐阅读
- flutter - Flutter Web - 如何在 ListView 中隐藏滚动条?
- amazon-web-services - 是否可以使用 AWS 转录将人员映射到转录本?
- c# - 如何将此逻辑从 LabVIEW 转换为 C# - 十六进制字符串到字节数组并将字节数组类型转换为单个
- javascript - Nodejs:TypeError:require()。()不是一个函数
- database - GridDB 中命名环境变量的约定是什么?
- sql - 如何提取嵌套的json?
- oracle - Sqlldr 日志在面对 ORA-01722 时显示错误的列名
- python - 如何在获取之前“实例化”torpy会话
- python - 使用 ev3dev2 库控制直流电机速度
- image - Dataframe.zip 仅作为单个输入