| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- //
- // json.hpp
- // json
- //
- // Created by Sam Jaffe on 1/30/16.
- // Copyright © 2016 Sam Jaffe. All rights reserved.
- //
- #ifndef json_hpp
- #define json_hpp
- #include <map>
- #include <vector>
- #include <utility>
- #include "../variant/variant.hpp"
- #include "json_common.h"
- #define JSON_TYPE_LIST \
- X(object) \
- X(array) \
- X(string) \
- X(double) \
- X(int) \
- X(bool)
- namespace json {
- class value;
- namespace parser {
- template <typename T> void parse(T& json, char const* data);
- template <typename T> void parse(T& json, std::string const& str);
- template <typename T> void parse(T& json, std::istream & in);
- }
-
- class value {
- public:
- using object_jt = std::map<std::string, value>;
- using array_jt = std::vector<value>;
- using string_jt = std::string;
- using double_jt = double;
- using int_jt = int32_t;
- using bool_jt = bool;
- private:
- static const value null_value;
-
- using data_t = variant<object_jt, array_jt, string_jt, double_jt, int_jt, bool_jt>;
- data_t data;
- public:
- #define X(type) bool is_##type() const { return data.is<type##_jt>(); }
- JSON_TYPE_LIST
- #undef X
- bool is_null() const { return !data.valid(); }
-
- value() = default;
- value(value const&) = default;
- value(value &&) = default;
- value& operator=(value const&) = default;
- value& operator=(value &&) = default;
- #define X(type) value(type##_jt val) { data.set<type##_jt>(std::move(val)); }
- JSON_TYPE_LIST
- #undef X
- #define X(type) value(type##_jt && val) { data.set<type##_jt>(std::forward<type##_jt>(val)); }
- JSON_TYPE_LIST
- #undef X
- #define X(type) value& operator=(type##_jt val) { data.set<type##_jt>(std::move(val)); return *this; }
- JSON_TYPE_LIST
- #undef X
-
- void parse(char const* data);
- void parse(std::string const& str);
- void parse(std::istream & in);
-
- void clear() { data = data_t(); }
-
- value& operator[](const size_t idx);
- value const& operator[](const size_t idx) const;
- value& operator[](std::string const& key);
- value const& operator[](std::string const& key) const;
-
- string_jt const& as_string() const;
- double_jt as_double() const;
- int_jt as_int() const;
- bool_jt as_bool() const;
-
- operator string_jt const&() const { return as_string(); }
- operator double_jt() const { return as_double(); }
- operator int_jt() const { return as_int(); }
- operator bool_jt() const { return as_bool(); }
-
- };
- #undef JSON_TYPE_LIST
- }
- #endif /* json_hpp */
|