base.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * Copyright (C) 2021 Duowan Inc. All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing,
  11. * software distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <iostream>
  17. #include "xpack/json.h" // 包含这个头文件
  18. using namespace std;
  19. struct User {
  20. int64_t id;
  21. string name;
  22. string mail;
  23. User(int64_t i=0, const string& n="", const string& m=""):id(i),name(n),mail(m){}
  24. XPACK(O(id, name, mail)); // 添加宏定义XPACK在结构体定义结尾
  25. };
  26. struct Group {
  27. string name;
  28. int64_t master;
  29. map<int, string> flags;
  30. vector<User> members;
  31. User arrays[2];
  32. XPACK(O(name, master, flags, members, arrays)); // 添加宏定义XPACK在结构体定义结尾
  33. };
  34. int main(int argc, char *argv[]) {
  35. (void)argc;
  36. (void)argv;
  37. Group g;
  38. g.name = "C++";
  39. g.master = 2019;
  40. g.members.resize(2);
  41. g.members[0] = User(1, "Jack", "jack@xpack.com");
  42. g.members[1] = User(2, "Pony", "pony@xpack.com");
  43. g.arrays[0] = g.members[0];
  44. g.arrays[1] = g.members[1];
  45. g.flags[1] = "a";
  46. g.flags[2] = "b";
  47. string json = xpack::json::encode(g); // 结构体转json
  48. cout<<json<<endl;
  49. Group n;
  50. xpack::json::decode(json, n); // json转结构体
  51. cout<<n.name<<endl;
  52. cout<<xpack::json::encode(n)<<endl;
  53. vector<int> vi;
  54. xpack::json::decode("[1,2,3]", vi); // 直接转换vector
  55. cout<<vi.size()<<','<<vi[1]<<endl;
  56. map<string, int> m;
  57. xpack::json::decode("{\"1\":10, \"2\":20}", m); // 直接转换map
  58. cout<<m.size()<<','<<m["2"]<<endl;
  59. return 0;
  60. }