Archive / / json.h
2011-05-29 19:42:57 UTC
previous next
#include <string> #include <sstream> #include <map> #include <vector> namespace json { // TODO add error handling class JsonObject { public: enum Type { AssocArray, Array, String, Integer, True, False, Null }; JsonObject() { _type = Null; } JsonObject(Type type) { _type = type; } JsonObject(std::string str) { _type = String; _string = str; } JsonObject(bool b) { if (b) _type = True; else _type = False; } JsonObject(int i) { _type = Integer; _integer = i; } std::string to_string() { std::ostringstream result; bool first; std::map<std::string, JsonObject>::iterator assoc_iter; std::vector<JsonObject>::iterator array_iter; switch (_type) { case AssocArray: first = true; result << "{"; for (assoc_iter = _assoc_items.begin(); assoc_iter != _assoc_items.end(); assoc_iter++) { if (first) first = false; else result << ","; // TODO escape the key result << "\"" << assoc_iter->first << "\":" << assoc_iter->second.to_string(); } result << "}"; break; case Array: first = true; result << "["; for (array_iter = _array_items.begin(); array_iter != _array_items.end(); array_iter++) { if (first) first = false; else result << ","; result << array_iter->to_string(); } result << "]"; break; case String: // TODO escape this string result << "\"" << _string << "\""; break; case Integer: result << _integer; break; case True: result << "true"; break; case False: result << "false"; break; case Null: result << "null"; break; } return result.str(); } JsonObject& operator[](const std::string& str) { return _assoc_items[str]; } JsonObject& operator[](const int index) { return _array_items[index]; } JsonObject& operator=(const int integer) { _type = Integer; _integer = integer; return *this; } JsonObject& operator=(const std::string str) { _type = String; _string = str; return *this; } JsonObject& operator=(const bool b) { _type = (b) ? True : False; return *this; } private: Type _type; std::map<std::string, JsonObject> _assoc_items; std::vector<JsonObject> _array_items; std::string _string; int _integer; }; }