json-data.cpp 1.7 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 Example {
  20. string type;
  21. xpack::JsonData data;
  22. XPACK(O(type, data));
  23. };
  24. struct Range {
  25. int min;
  26. int max;
  27. XPACK(O(min, max));
  28. };
  29. struct User {
  30. int id;
  31. string name;
  32. XPACK(O(id, name));
  33. };
  34. static void test(const std::string &data) {
  35. Example e;
  36. xpack::json::decode(data, e);
  37. if (e.type == "range") {
  38. Range r;
  39. e.data.decode(r);
  40. cout<<"range. min:"<<r.min<<", max:"<<r.max<<endl;
  41. cout<<e.data["min"].GetInt()<<endl;
  42. cout<<"raw:"<<e.data.String()<<endl;
  43. } else if (e.type == "user") {
  44. User u;
  45. e.data.decode(u);
  46. cout<<"user. id:"<<u.id<<", name:"<<u.name<<endl;
  47. cout<<"raw:"<<e.data.String()<<endl;
  48. } else {
  49. cout<<"unknow type"<<endl;
  50. }
  51. cout<<"re encode:"<<xpack::json::encode(e)<<endl;
  52. }
  53. int main(int argc, char *argv[]) {
  54. (void)argc;
  55. (void)argv;
  56. string s1 = "{\"type\":\"range\", \"data\":{\"min\":12, \"max\":22}}";
  57. string s2 = "{\"type\":\"user\", \"data\":{\"id\":123, \"name\":\"xpack\"}}";
  58. test(s1);
  59. test(s2);
  60. return 0;
  61. }