#pragma once #ifdef TEST_JSON #include class refer { volatile int32_t ref_; std::mutex mutex_; protected: refer() : ref_(1) {} virtual ~refer() {} virtual void on_born(void) {} virtual void on_dead(void) {} public: virtual int32_t add_ref(void) { std::lock_guard l(mutex_); return ++ref_; } virtual int32_t release(void) { int32_t ref; { std::lock_guard l(mutex_); ref = --ref_; } if (ref == 0) { delete this; } return ref; } }; #else #include "../referer.h" #endif #include #include struct cJSON; class json : public refer { enum val_type { VAL_TYPE_NULL = 0, VAL_TYPE_BOOL, VAL_TYPE_INT, VAL_TYPE_FLOAT, VAL_TYPE_STRING, VAL_TYPE_OBJECT, VAL_TYPE_ARRAY, }; val_type type_; std::string key_; union { bool bval; int nval; double dval; }simple_val_; std::string strval_; std::vector arr_val_; size_t cur_child_; static std::string object_key(json* jsn); static std::string array_key(json* jsn); void from_cjson(cJSON* cj); json* find_child(const char* key, bool remove = false); public: json(char* json_txt = 0); protected: json(const char* key, bool val); json(const char* key, int val); json(const char* key, double val); json(const char* key, const char* val); ~json(); public: // parse/un-parse ... bool attach_text(char* json_txt); void clear(bool as_array = false); std::string to_string(void); // attributes ... std::string& key(void); bool is_array(void); bool is_leaf_node(void); // whether this object is a leaf node contains final value // value access ... bool get_value(const char* key, bool& val); bool get_value(const char* key, int& val); bool get_value(const char* key, double& val); bool get_value(const char* key, std::string& val); bool get_value(const char* key, json*& val); // enumeration ... size_t children(void); // return children count if was object or array, or else -1 returned json* child(size_t ind); json* first_child(void); json* next_child(void); // change the item matching 'key', otherwise add a new item bool set_value(const char* key, bool val); bool set_value(const char* key, int val); bool set_value(const char* key, double val); bool set_value(const char* key, const char* val); bool set_value(const char* key, json* val); // operator+= only for array json& operator+=(bool val); json& operator+=(int val); json& operator+=(double val); json& operator+=(const char* val); json& operator+=(json* val); // remove item json& operator-=(int ind); bool remove(const char* key); bool remove(json* child); bool remove(int ind); // position management int index(json* child); int index_move_to(json* child, int ind); // leaf node value ... bool value(bool& val); bool value(int& val); bool value(double& val); bool value(std::string& val); json& operator=(bool val); json& operator=(int val); json& operator=(double val); json& operator=(const char* val); };