json_decoder.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::JsonDecoder jd(json, false);
  51. jd["name"].decode(NULL, n.name, NULL);
  52. cout<<"name is:"<<n.name<<endl;
  53. xpack::JsonDecoder&flags = jd["flags"];
  54. for (xpack::JsonDecoder::Iterator it=flags.Begin(); it!=flags.End(); ++it) {
  55. string f;
  56. it.Val().decode(NULL, f, NULL);
  57. cout<<" "<<it.Key()<<':'<<f<<endl;
  58. }
  59. return 0;
  60. }