ZBLOG

yaml-cpp 自定解析结构体 struct AppAllNamespace std::vector vec; }; 使用encode和decode

方法对结构体进行序列化和反序列化:

  1. #include <yaml-cpp/yaml.h>
  2. struct NsStore {
  3. std::string ns_name;
  4. std::string store_name;
  5. };
  6. struct AppAllNamespace {
  7. std::vector<NsStore> vec;
  8. };
  9. namespace YAML {
  10. template<>
  11. struct convert<NsStore> {
  12. static Node encode(const NsStore& ns_store) {
  13. Node node;
  14. node["ns_name"] = ns_store.ns_name;
  15. node["store_name"] = ns_store.store_name;
  16. return node;
  17. }
  18. static bool decode(const Node& node, NsStore& ns_store) {
  19. if (!node.IsMap() || node.size() != 2) {
  20. return false;
  21. }
  22. ns_store.ns_name = node["ns_name"].as<std::string>();
  23. ns_store.store_name = node["store_name"].as<std::string>();
  24. return true;
  25. }
  26. };
  27. template<>
  28. struct convert<AppAllNamespace> {
  29. static Node encode(const AppAllNamespace& app_all_ns) {
  30. Node node;
  31. for (const auto& ns_store : app_all_ns.vec) {
  32. node.push_back(ns_store);
  33. }
  34. return node;
  35. }
  36. static bool decode(const Node& node, AppAllNamespace& app_all_ns) {
  37. if (!node.IsSequence()) {
  38. return false;
  39. }
  40. app_all_ns.vec.clear();
  41. for (const auto& ns_node : node) {
  42. NsStore ns_store;
  43. if (!ns_node.as<NsStore>(ns_store)) {
  44. return false;
  45. }
  46. app_all_ns.vec.push_back(ns_store);
  47. }
  48. return true;
  49. }
  50. };
  51. }
  52. int main() {
  53. AppAllNamespace app_all_ns;
  54. app_all_ns.vec.push_back({"ns1", "store1"});
  55. app_all_ns.vec.push_back({"ns2", "store2"});
  56. // 序列化为 YAML 字符串
  57. std::cout << YAML::Dump(app_all_ns) << std::endl;
  58. // 从 YAML 字符串反序列化回来
  59. AppAllNamespace decoded_app_all_ns = YAML::Load<AppAllNamespace>(R"(
  60. - ns_name: ns1
  61. store_name: store1
  62. - ns_name: ns2
  63. store_name: store2
  64. )");
  65. for (const auto& ns_store : decoded_app_all_ns.vec) {
  66. std::cout << ns_store.ns_name << ", " << ns_store.store_name << std::endl;
  67. }
  68. return 0;
  69. }

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=254

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?