1 #include "JsonFormatter.hpp"
2 #include "Attribute.hpp"
3 #include "ProfileAttribute.hpp"
5 #include <Poco/JSON/Parser.h>
6 #include <Poco/DateTime.h>
7 #include <Poco/DateTimeParser.h>
11 Poco::JSON::Object::Ptr
12 gde::JsonFormatter::parse(const std::string& json)
14 Poco::JSON::Parser parser;
15 Poco::Dynamic::Var result = parser.parse(json);
16 // use pointers to avoid copying
17 Poco::JSON::Object::Ptr object = result.extract<Poco::JSON::Object::Ptr>();
23 gde::JsonFormatter::extract(Poco::JSON::Object::Ptr object, const std::string& varName)
26 Poco::Dynamic::Var v = object->get(varName);
27 return v.convert<T>();
28 } catch (Poco::InvalidAccessException& e) {
29 // This exception is raised if Var v is empty
36 gde::JsonFormatter::extractVector(Poco::JSON::Object::Ptr object, const std::string& varName)
39 std::vector<T> result;
40 Poco::JSON::Array::Ptr array = object->getArray(varName);
41 typedef Poco::JSON::Array::ConstIterator ArrayIterator;
43 for (ArrayIterator itr = array->begin(); itr != array->end(); ++itr) {
44 std::string json = itr->toString(); // { var:value, ... }
45 result.push_back(T::fromJson(json));
49 } catch (Poco::InvalidAccessException& e) {
50 // This exception is raised if Var v is empty
51 return std::vector<T>();
56 gde::JsonFormatter::extract(Poco::JSON::Object::Ptr object, const std::string& varName)
59 Poco::Dynamic::Var v = object->get(varName);
60 std::string formattedDate = v.convert<std::string>();
64 Poco::DateTimeParser::parse(formattedDate, dt, tzd);
65 return dt.timestamp();
66 } catch (Poco::InvalidAccessException& e) {
67 // This exception is raised if Var v is empty
68 return Poco::Timestamp(); // Return current time; not so good, should return nil object
73 gde::JsonFormatter::stringify(const Poco::JSON::Object& object) {
74 std::ostringstream jsonStream;
75 object.stringify(jsonStream);
76 return jsonStream.str();
80 gde::JsonFormatter::format(const std::string txt, int value)
82 std::ostringstream oss;
87 gde::JsonFormatter::format(const std::string txt, const std::string& value)
89 std::ostringstream oss;
90 oss << txt << "\"" << value << "\"";
94 gde::JsonFormatter::format(const std::string txt, bool value)
96 std::ostringstream oss;
97 oss << txt << (value?"true":"false");
101 // Declare methods for the supported template type parameters
102 template int gde::JsonFormatter::extract<int>(Poco::JSON::Object::Ptr, const std::string&);
103 template bool gde::JsonFormatter::extract<bool>(Poco::JSON::Object::Ptr, const std::string&);
104 template std::string gde::JsonFormatter::extract<std::string>(Poco::JSON::Object::Ptr, const std::string&);
106 template std::vector<gde::Attribute> gde::JsonFormatter::extractVector<gde::Attribute>(Poco::JSON::Object::Ptr, const std::string&);
107 template std::vector<gde::ProfileAttribute> gde::JsonFormatter::extractVector<gde::ProfileAttribute>(Poco::JSON::Object::Ptr, const std::string&);