基础序列化
本页介绍基础对象图序列化和核心序列化 API。
对象图序列化
Apache Fory™ 提供复杂对象图的自动序列化,保留对象之间的结构和关系。FORY_STRUCT 宏在编译时生成高效的序列化代码,消除运行时开销。
核心功能:
- 支持任意深度的嵌套结构体序列化
- 集合类型(vector、set、map)
- 使用
std::optional<T>的可选字段 - 智能指针(
std::shared_ptr、std::unique_ptr) - 自动处理基本类型和字符串
- 使用变长整数的高效二进制编码
#include "fory/serialization/fory.h"
#include <vector>
#include <map>
using namespace fory::serialization;
// 定义结构体
struct Address {
std::string street;
std::string city;
std::string country;
bool operator==(const Address &other) const {
return street == other.street && city == other.city &&
country == other.country;
}
};
FORY_STRUCT(Address, street, city, country);
struct Person {
std::string name;
int32_t age;
Address address;
std::vector<std::string> hobbies;
std::map<std::string, std::string> metadata;
bool operator==(const Person &other) const {
return name == other.name && age == other.age &&
address == other.address && hobbies == other.hobbies &&
metadata == other.metadata;
}
};
FORY_STRUCT(Person, name, age, address, hobbies, metadata);
int main() {
auto fory = Fory::builder().xlang(true).build();
fory.register_struct<Address>(100);
fory.register_struct<Person>(200);
Person person{
"John Doe",
30,
{"123 Main St", "New York", "USA"},
{"reading", "coding"},
{{"role", "developer"}}
};
auto result = fory.serialize(person);
auto decoded = fory.deserialize<Person>(result.value());
assert(person == decoded.value());
}
序列化 API
序列化到新 Vector
auto fory = Fory::builder().xlang(true).build();
fory.register_struct<MyStruct>(1);
MyStruct obj{/* ... */};
// 序列化 - 返回 Result<std::vector<uint8_t>, Error>
auto result = fory.serialize(obj);
if (result.ok()) {
std::vector<uint8_t> bytes = std::move(result).value();
// 使用 bytes...
} else {
// 处理错误
std::cerr << result.error().to_string() << std::endl;
}