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

时间:2018-08-31 15:58:35

标签: ballerina

在使用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;
};

2 个答案:

答案 0 :(得分:1)

我相信这是预期的方式。由于它是时间类型而不是字符串,因此可以访问时间的各个组成部分。

如果您需要一个字符串,则您的字段应为字符串类型字段,并且可以使用time.toString()方法填充其值

答案 1 :(得分:0)

这是有意的,因为在对象到json或记录到json转换期间,公共字段会转换为json键值对。 | to_timestamp | |----------------------| | 1943-03-09T01:00:00Z | 方法在Ballerina中返回一个time:createTime对象,可以在以下位置查看其定义:

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

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

此行为与json到记录/地图转换的行为一致。

目前无法将对象的行为更改为json转换。您可以请求使用此功能here