json.h 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. #ifndef __X_PACK_JSON_H
  17. #define __X_PACK_JSON_H
  18. #include "json_decoder.h"
  19. #include "json_encoder.h"
  20. #include "json_data.h"
  21. #include "xpack.h"
  22. namespace xpack {
  23. class json {
  24. public:
  25. template <class T>
  26. static void decode(const std::string &data, T &val) {
  27. JsonDecoder doc(data);
  28. doc.decode(NULL, val, NULL);
  29. }
  30. template <class T>
  31. static void decode(const rapidjson::Value &data, T &val) {
  32. JsonDecoder doc(&data);
  33. doc.decode(NULL, val, NULL);
  34. }
  35. template <class T>
  36. static void decode_file(const std::string &file_name, T &val) {
  37. JsonDecoder doc(file_name, true);
  38. doc.decode(NULL, val, NULL);
  39. }
  40. template <class T>
  41. static std::string encode(const T &val) {
  42. JsonEncoder doc(-1);
  43. doc.encode(NULL, val, NULL);
  44. return doc.String();
  45. }
  46. template <class T>
  47. static std::string encode(const T &val, int flag, int indentCount, char indentChar) {
  48. JsonEncoder doc(indentCount, indentChar);
  49. Extend ext(flag, NULL);
  50. doc.encode(NULL, val, &ext);
  51. return doc.String();
  52. }
  53. };
  54. }
  55. #endif