如何将Ballerina记录值序列化为byte[]及从byte[]反序列化?
Ballerina记录与byte[]的序列化/反序列化实现
下面是针对Employee记录完成序列化(转byte[])和反序列化(从byte[]转记录)的完整代码实现:
type Employee record {| int id; string firstName; string lastName; |}; function toBytes(Employee employee) returns byte[] { // 1. 将记录转换为JSON值 json employeeJson = employee; // 2. 将JSON值转换为字符串 string jsonStr = employeeJson.toString(); // 3. 将字符串编码为UTF-8字节数组 return jsonStr.toBytes("UTF-8"); } function toEmployee(byte[] bytes) returns Employee|error { // 1. 将字节数组解码为UTF-8字符串 string|error jsonStr = string:fromBytes(bytes, "UTF-8"); if jsonStr is error { return jsonStr; } // 2. 将字符串解析为JSON值 json|error employeeJson = json.fromString(jsonStr); if employeeJson is error { return employeeJson; } // 3. 将JSON值转换为Employee记录,类型不匹配时返回错误 return employeeJson.cloneWithType(Employee); }
代码说明
- 序列化逻辑:
- 利用Ballerina的自动类型转换,直接将
Employee记录转为json值 - 把JSON值转为字符串后,通过
string:toBytes()编码为UTF-8格式的字节数组
- 利用Ballerina的自动类型转换,直接将
- 反序列化逻辑:
- 先将字节数组解码为UTF-8字符串,处理解码错误
- 解析字符串为JSON值,处理解析错误
- 使用
cloneWithType()将JSON值转换为Employee记录,若JSON结构与记录不匹配会返回类型错误
示例使用
public function main() { Employee emp = {id: 1, firstName: "John", lastName: "Doe"}; byte[] empBytes = toBytes(emp); io:println("Serialized bytes length: ", empBytes.length()); Employee|error decodedEmp = toEmployee(empBytes); if decodedEmp is Employee { io:println("Deserialized employee: ", decodedEmp.firstName, " ", decodedEmp.lastName); } else { io:println("Deserialization failed: ", decodedEmp.message()); } }
内容的提问来源于stack exchange,提问作者Ayesh Almeida
相关产品推荐
相关产品推荐

