将记录转换为包含 time:Time 类型(或任何其他对象类型)的 JSON



在使用Ballerina开发应用程序时,我正在使用记录类型来定义"事件"数据结构。

public type Event record {
string eventType;
time:Time eventTime;
};

将事件记录转换为 JSON 时,反之亦然,将非简单值转换为 JSON 时,我应该期待什么?

我的经验是,对象内部字段结构的字符串表示形式被生成为输出。 我实际上期望在转换为 JSON 时,将调用 time.toString(( 方法。这种行为是故意的吗,我能影响这种行为吗?

问候罗布

------ actual output --------------------------
2018-08-31 17:21:51,865 INFO  [] - {"eventType":"OrderAccepted", "eventTime":{"time":1535742000000, "zone":{"zoneId":"+02:00", "zoneOffset":7200}}}  
------ expected output ------------------------
2018-08-31 17:21:51,865 INFO  [] - {"eventType":"OrderAccepted", "eventTime": "2018-08-31T21:00:00+02:00"}

使用的芭蕾舞演员代码:

import ballerina/log;
import ballerina/time;
function main(string... args) {
json je = testTimeToJson();
log:printInfo(je.toString());
}
function testTimeToJson() returns json {
Event event = {};
event.eventType = "OrderAccepted";
event.eventTime = time:createTime(2018, 8, 31, 21, 0, 0, 0, "+02:00");
return check <json>event;
}
public type Event record {
string eventType;
time:Time eventTime;
};

我相信这是预期的方式。这允许访问时间的各个组成部分,因为它的类型是时间而不是字符串。

如果你需要一个字符串,你的字段应该是一个字符串类型的字段,它的值可以使用time.toString((方法填充。

这是有意为之的,因为在对象到 json 或记录到 json 转换期间,公共字段将转换为 json 键值对。time:createTime方法返回 Ballerina 中的Time对象,可以在以下位置查看其定义:

https://github.com/ballerina-platform/ballerina-lang/blob/62ace431ac7d0645d117072216adc70eb16911d6/stdlib/time/src/main/ballerina/time/timelib.bal#L36

当它转换为 json 时,其公共字段将转换为键值对。递归Timezone的公共字段也会根据其公共字段转换为键值对。

此行为与 json 记录/映射转换一致。

目前无法更改对象到 json 转换的行为。您可以在此处请求此功能。

相关内容

最新更新