首页 > 解决方案 > 将记录转换为包含 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;
};

标签: ballerina

解决方案


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

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


推荐阅读