首页 > 解决方案 > 如何将带有保留关键字的 JSON 有效负载转换为名称以在 Ballerina 中记录

问题描述

我正在开发一个 Ballerina 服务,该服务接收事件并使用该convert函数将 JSON 有效负载转换为记录。该事件包含一个名称type为 Ballerina 中保留关键字的字段。我无法更改事件的有效负载。string type;以下是一个简化的示例代码,由于记录中的原因,无法编译Event。更改typeTypeeventType允许编译,但执行会引发错误,因为 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-conversionballerina

解决方案


您可以按如下方式定义事件:

type Event record {
    string id;
    string 'type;    
    string time;
};

The'用于转义 Ballerina 中的关键字。访问它时,您也可以将其用作event.'type

在这里您可以找到一个示例用法。


推荐阅读