I am parsing a json file using nlohmann's json.hpp. The part of the json file I am concerned with looks like this:
"image_captureOptions": {
"captureInterval" : 1000,
"captureLimit" : 5,
"imageExtension" : "jpg",
"imageResizeDims" : [640, 480]
},
...
The relevant parts of the class that parses the json look like this:
namespace json = nlohmann;
class ConfigReader {
json::json data;
void readConfigFile(std::string path) {
std::ifstream inputStream(path);
inputStream >> data;
}
public:
ConfigReader() {
static const std::string defaultPath = "config.json";
readConfigFile(defaultPath);
}
int getImageCaptureInterval() { return data["image_captureOptions"]["captureInterval"]; }
int getImageCaptureLimit() { return data["image_captureOptions"]["captureLimit"]; }
std::string getImageExtension() { return data["image_captureOptions"]["imageExtension"]; }
???? getImageResizeDims() { return data["image_captureOptions"]["imageResizeDims"]; }
};
The question marks on the last line represent my confusion on how to specify the return type of that function.
One of the nice things about this library is that conversions to standard types are built-in and do the things you want them to do (the library also provides for a mechanism to do conversions to and from user-provided types).
In this case, you can just use that:
std::vector<int> getImageResizeDims() {
return data["image_captureOptions"]["imageResizeDims"];
}
If the json subobject at runtime can't be converted to a std::vector<int>
, that conversion will throw a type_error
.