jsoncpp version: jsoncpp-1.8.4
Basic Operations
#include <json/json.h>
int main() {
Json::Value root;
root["key1"] = 1;
root["key2"] = "good";
root["indent"]["length"] = 2;
root["indent"]["use_space"] = true;
Json::Value v(Json::arrayValue);
v[0] = "clojure";
v[1] = "json";
v[2] = "xml";
root["key3"] = v;
return 0;
}
Walk the type
for (auto i = root.begin(); i != root.end(); i++) {
Json::Value& obj = *i;
const std::string name = i.name();
std::cout << name << "-" << i.key() << ": " << obj.isArray() << "\n";
}
Read
Json::Value root;
std::ifstream infile;
infile.open("your.json", std::ios::in);
try {
infile >> root;
} catch (std::exception& e) {
root = Json::objectValue;
}
infile.close();
Here is the inflow to read the file, it can be textstringstream
Write
std::ofstream of;
of.open("your.json", std::ios::out);
of << root << std::endl;
of.flush();
of.close();
Formatted output
The default output json indentation is \t
that if we wanted to change two spaces:
Json::StreamWriterBuilder builder;
builder["indentation"] = " ";
builder.newStreamWriter()->write(root, &std::cout);
Here is a confusing place:
void StreamWriterBuilder::setDefaults(Json::Value* settings)
seem to make a settings object becomes StreamWriterBuilder
global default configuration, but is really just reset the configuration to make a 'default' data, the usage is really baffling ...
void StreamWriterBuilder::setDefaults(Json::Value* settings) {
//! [StreamWriterBuilderDefaults]
(*settings)["commentStyle"] = "All";
(*settings)["indentation"] = "\t";
(*settings)["enableYAMLCompatibility"] = false;
(*settings)["dropNullPlaceholders"] = false;
(*settings)["useSpecialFloats"] = false;
(*settings)["precision"] = 17;
(*settings)["precisionType"] = "significant";
//! [StreamWriterBuilderDefaults]
}