1 // ANNA - Anna is Not Nothingness Anymore //
3 // (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo //
5 // See project site at http://redmine.teslayout.com/projects/anna-suite //
6 // See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE //
9 #ifndef anna_json_SaxConsumer_hpp
10 #define anna_json_SaxConsumer_hpp
15 #include <anna/json/json.hpp> // nlohmann::json
16 #include <anna/core/util/defines.hpp>
22 class SaxConsumer : public nlohmann::json::json_sax_t
25 bool started_, last_was_start_, last_was_array_;
26 std::stringstream result_;
27 std::stringstream current_object_;
28 std::stack<std::string> nodes_stack_;
33 SaxConsumer() : started_(false), last_was_start_(false), last_was_array_(false), indent_(-ANNA_XML_INDENTATION_SPACES) {}
35 const std::stringstream & getResult() const { return result_; }
39 current_object_ << "<null>";
40 last_was_start_ = false;
44 bool boolean(bool val) override
46 current_object_ << std::quoted(val ? "true" : "false");
47 last_was_start_ = false;
51 bool number_integer(number_integer_t val) override
53 current_object_ << std::quoted(std::to_string(val));
54 last_was_start_ = false;
58 bool number_unsigned(number_unsigned_t val) override
60 current_object_ << std::quoted(std::to_string(val));
61 last_was_start_ = false;
65 bool number_float(number_float_t val, const string_t& s) override
67 current_object_ << std::quoted(s);
68 last_was_start_ = false;
72 bool string(string_t& val) override
74 current_object_ << std::quoted(val);
75 last_was_start_ = false;
79 bool start_object(std::size_t elements) override
81 if (!started_) { started_ = true ; return true; }
82 indent_ += ANNA_XML_INDENTATION_SPACES;
83 if (last_was_start_) result_ << ">\n";
84 last_was_start_ = true;
85 if (!last_was_array_) nodes_stack_.push(key_);
86 result_ << std::string(indent_, ' ') << "<" << nodes_stack_.top();
87 if (last_was_array_) nodes_stack_.push(key_);
88 last_was_array_ = false;
92 bool end_object() override
94 std::string close = "/>";
95 if (current_object_.str().empty()) close = "";
96 result_ << current_object_.str() << close;
97 if (indent_ < 0) return true;
98 if (close == "") result_ << std::string(indent_, ' ') << "</" << nodes_stack_.top() << ">";
99 indent_ -= ANNA_XML_INDENTATION_SPACES;
101 current_object_.str("");
106 bool start_array(std::size_t elements) override
108 nodes_stack_.push(key_);
109 result_ << current_object_.str() << ">\n";
110 current_object_.str("");
114 bool end_array() override
117 last_was_array_ = true;
121 bool key(string_t& val) override
127 current_object_ << " " << val.substr(1) << "=";
132 bool parse_error(std::size_t position, const std::string& last_token, const nlohmann::json::exception& ex) override
134 result_ << std::string(ex.what());