如何将 Ballerina 记录值序列化到 `byte[]` 或从 `byte[]` 进行反序列化?

问题描述 投票:0回答:1

我有一个 Ballerina 记录值,我需要将其序列化为

byte[]
,当提供
byte[]
时,我需要将其反序列化为相应的记录值。这是我当前的代码:

type Employee record {|
    int id;
    string firstName;
    string lastName;
|};

function toBytes(Employee employee) returns byte[] {
    // serialization logic
}

function toEmployee(byte[] bytes) returns Employee|error {
    // deserialization logic
}
serialization deserialization ballerina ballerina-swan-lake
1个回答
0
投票

如果您需要将记录值转换为

byte[]
,反之亦然,您可以按照以下方法操作:

# Convert a record value to bytes
Record value -> String -> Bytes

# Convert bytes into a record value
Bytes -> String -> Record value

要将记录值转换为字符串,您可以使用记录的 Ballerina 特定字符串表示形式或记录的 JSON 表示形式。

这里有两种实现转换的方法:

  1. 使用 Ballerina 特定的字符串表示:
function toBytes(Employee employee) returns byte[] {
    string balString = employee.toBalString();
    return balString.toBytes();
}

function toEmployee(byte[] bytes) returns Employee|error {
    string balString = check string:fromBytes(bytes);
    return (check balString.fromBalString()).cloneWithType();
}
  1. 使用标准 JSON 表示:
function toBytes(Employee employee) returns byte[] {
    string jsonString = employee.toJsonString();
    return jsonString.toBytes();
}

function toEmployee(byte[] bytes) returns Employee|error {
    string jsonString = check string:fromBytes(bytes);
    return jsonString.fromJsonStringWithType();
}

有关更多信息,请参阅

toBalString
toJsonString
函数的文档。

请注意,Ballerina 语言规范中有一个关于直接记录到字节转换的“未解决问题”,尚未实现。

© www.soinside.com 2019 - 2024. All rights reserved.