Browse Source

Adding support in object binder to throw an exception if there are any keys that were missing.

Samuel Jaffe 8 years ago
parent
commit
c86688cd01
2 changed files with 9 additions and 2 deletions
  1. 7 1
      json/json_object_binder.hpp
  2. 2 1
      json_common.hpp

+ 7 - 1
json/json_object_binder.hpp

@@ -20,7 +20,7 @@ namespace json { namespace binder {
     object_binder& operator()(std::string const&k, V T::*ptr, binder_impl<V> const&v) {
       return (*this)(k, binder<T>(new direct_binder<T, V>(ptr, binder<V>(v) )));
     }
-    
+
     object_binder& operator()(std::string const&k, binder<T> const&v) {
       mapping.emplace(k, v);
       return *this;
@@ -53,6 +53,8 @@ namespace json { namespace binder {
     
     void parse_object(T& object, char const*& data, parser::options opts) const {
       std::string key;
+      std::set<std::string> unparsed_keys;
+      for ( auto & p : mapping ) { unparsed_keys.insert(p.first); }
       while (*data && *data != '}') {
         if (json::helper::get_next_element(data) != '"') {
           throw json::malformed_json_exception(std::string("Expected object key starting with '\"', got '") + *data + "' instead");
@@ -63,6 +65,7 @@ namespace json { namespace binder {
         }
         auto it = mapping.find(key);
         if (it != mapping.end()) {
+          unparsed_keys.erase(key);
           it->second.parse(object, ++data, opts);
         } else if (opts & parser::disable_unknown_keys) {
           throw json::malformed_json_exception("Unexpected key " + key);
@@ -73,6 +76,9 @@ namespace json { namespace binder {
       }
       if (*data) ++data;
       else throw json::unterminated_json_exception("Reached end of parse string without finding object end");
+      if ( !unparsed_keys.empty() && opts & parser::disable_missing_keys ) {
+        throw json::malformed_json_exception("missing certain keys from object construction TODO");
+      }
     }
     
     template <typename E>

+ 2 - 1
json_common.hpp

@@ -63,7 +63,8 @@ namespace json { namespace parser {
   enum options {
     allow_all                        = 0x00,
     disable_unknown_keys             = 0x01,
-    disable_concatenated_json_bodies = 0x02,
+    disable_missing_keys             = 0x02,
+    disable_concatenated_json_bodies = 0x04,
     disable_all                      = 0xFF,
   };
 } }