jsoncpp.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #pragma once
  2. #include <memory>
  3. #include <type_traits>
  4. #include <json/value.h>
  5. #include <jvalidate/detail/simple_adapter.h>
  6. namespace jvalidate::adapter {
  7. template <typename JSON> class JsonCppAdapter;
  8. template <> struct AdapterTraits<Json::Value> {
  9. template <typename JSON> using Adapter = adapter::JsonCppAdapter<JSON>;
  10. using ConstAdapter = adapter::JsonCppAdapter<Json::Value const>;
  11. static Json::Value const & const_empty() {
  12. static Json::Value const g_value;
  13. return g_value;
  14. }
  15. };
  16. template <typename JSON> class JsonCppObjectAdapter : public detail::SimpleObjectAdapter<JSON> {
  17. public:
  18. using JsonCppObjectAdapter::SimpleObjectAdapter::SimpleObjectAdapter;
  19. bool contains(std::string const & key) const { return this->const_value().isMember(key); }
  20. JsonCppAdapter<JSON> operator[](std::string const & key) const {
  21. return this->value() ? &(*this->value())[key] : nullptr;
  22. }
  23. };
  24. template <typename JSON> class JsonCppAdapter final : public detail::SimpleAdapter<JSON> {
  25. private:
  26. JSON * value_;
  27. public:
  28. using JsonCppAdapter::SimpleAdapter::SimpleAdapter;
  29. Type type() const {
  30. switch (const_value().type()) {
  31. case Json::nullValue:
  32. return Type::Null;
  33. case Json::booleanValue:
  34. return Type::Boolean;
  35. case Json::realValue:
  36. return Type::Number;
  37. case Json::stringValue:
  38. return Type::String;
  39. case Json::arrayValue:
  40. return Type::Array;
  41. case Json::objectValue:
  42. return Type::Object;
  43. case Json::intValue:
  44. case Json::uintValue:
  45. return Type::Integer;
  46. }
  47. }
  48. bool as_boolean() const { return const_value().asBool(); }
  49. int64_t as_integer() const { return const_value().asInt64(); }
  50. double as_number() const { return const_value().asDouble(); }
  51. std::string as_string() const { return const_value().asString(); }
  52. JsonCppObjectAdapter<JSON> as_object() const { return value_; }
  53. static std::string key(auto it) { return it.key().asString(); }
  54. private:
  55. using JsonCppAdapter::SimpleAdapter::const_value;
  56. };
  57. }