JSON_Loader now handles key fetching safely (if we want)

This commit is contained in:
Chris Punches
2017-06-09 00:41:06 -04:00
parent ad7db62b8a
commit 3c52f94bfa
4 changed files with 102 additions and 121 deletions

View File

@@ -1,9 +1,11 @@
#include "Conf.h"
Conf::Conf( std::string filename ): JSON_Loader( filename )
Conf::Conf( std::string filename ): JSON_Loader()
{
this->plan_path = this->as_serialized()["plan_path"].asString();
this->units_path = this->as_serialized()["units_path"].asString();
this->load_json_file( filename, true );
this->plan_path = this->get_key("plan_path", true, false).asString();
this->units_path = this->get_key("units_path", true, false).asString();
};
std::string Conf::get_plan_path()

View File

@@ -71,7 +71,7 @@ int JSON_Loader::load_json_string( std::string input, bool verbose )
return 1;
} else {
// if in verbose mode, give the user an "it worked" message
if (verbose)
if ( verbose )
{
std::cout << "Successfully parsed JSON string with " << this->json_root.size() << " elements. Value:" << std::endl;
std::cout << input << std::endl;
@@ -92,4 +92,35 @@ Json::Value JSON_Loader::as_serialized()
std::string JSON_Loader::as_string()
{
return this->json_root.asString();
}
// returns the string representation of the value of a key
// the Jason::Value object to assign the fetched value to
// verbosity flag
// exit or not on failure
int JSON_Loader::get_key( Json::Value &input, std::string key, bool verbose, bool safety)
{
if ( this->json_root.isMember( key ) )
{
// key was found so return it
input = this->json_root[ key ];
return 0;
} else {
// key was not found
if ( verbose )
{
// verbose mode tells the user what key we were looking for.
std::cerr << "Failed to find key '" << key << "'." << std::endl;
return 1;
}
if ( ! safety )
{
// if we're not ignoring fatal errors
std::cout << "Exiting." << std::endl;
// exit code for failure
// this should probably be a 'throw'....
exit(1);
}
}
}

View File

@@ -28,5 +28,9 @@ public:
// return as a JSONCPP serialized object
Json::Value as_serialized();
std::string as_string();
// safely handle key retrieval (if we want it to be safe)
// next iter should be:
int JSON_Loader::get_key( Json::Value &input, std::string key, bool verbose, bool safety);
};
#endif //FTESTS_JLOADER_H