diff --git a/VirtualRobot/CMakeLists.txt b/VirtualRobot/CMakeLists.txt index 32faa086c6c28d543b40ec9f5d4bbc57520b5a66..ce8bc761577c803ceef53a9f3706fc573141a77f 100644 --- a/VirtualRobot/CMakeLists.txt +++ b/VirtualRobot/CMakeLists.txt @@ -353,6 +353,7 @@ SET(SOURCES Tools/Gravity.cpp Util/json/eigen_conversion.cpp + Util/json/io.cpp Util/xml/tinyxml2.cpp Visualization/ColorMap.cpp @@ -575,6 +576,7 @@ SET(INCLUDES Util/json/eigen_conversion.h Util/json/eigen_conversion.hpp + Util/json/io.h Util/json/json.hpp Util/xml/tinyxml2.h diff --git a/VirtualRobot/Util/json/io.cpp b/VirtualRobot/Util/json/io.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a18462d08665b4d7604747bbe1b09944b4ed235d --- /dev/null +++ b/VirtualRobot/Util/json/io.cpp @@ -0,0 +1,35 @@ +#include "io.h" + +#include <iostream> +#include <fstream> + + +namespace nlohmann +{ + + json read_json(const std::string& filename) + { + std::ifstream ifs; + // Allow throwing std::ios_base::failure. + ifs.exceptions(std::ifstream::failbit | std::ifstream::badbit); + + ifs.open(filename); + json j; + ifs >> j; + return j; + } + + void write_json(const std::string& filename, const json& j, + const int indent, const char indent_char) + { + std::ofstream ofs; + // Allow throwing std::ios_base::failure. + ofs.exceptions(std::ifstream::failbit | std::ifstream::badbit); + + ofs.open(filename); + ofs << j.dump(indent, indent_char); + } + +} + + diff --git a/VirtualRobot/Util/json/io.h b/VirtualRobot/Util/json/io.h new file mode 100644 index 0000000000000000000000000000000000000000..9bf4f907c2dc64d997e8770a157daac1fece1efc --- /dev/null +++ b/VirtualRobot/Util/json/io.h @@ -0,0 +1,34 @@ +#pragma once + +#include "json.hpp" + + +namespace nlohmann +{ + + /** + * @brief Read a JSON document from the given file. + * + * @param filename The name of the file to read from. + * @return The JSON document. + * + * @throw std::ios_base::failure If IO access fails. + */ + json read_json(const std::string& filename); + + + /** + * @brief Write a JSON document to the given file. + * + * @param j The JSON document. + * @param filename The name of the file to write to. + * @param indent See nlohmann::json::dump(). + * @param indent_char See nlohmann::json::dump(). + * + * @throw std::ios_base::failure If IO access fails. + */ + void write_json(const std::string& filename, const json& j, + const int indent = -1, const char indent_char = ' '); + + +}