Created
April 18, 2023 08:39
-
-
Save shawnfeng0/e25896cd65be13c0c77e68fdfd395baa to your computer and use it in GitHub Desktop.
jsoncpp usage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int main(void) { | |
std::string raw = "{\"test\": 1}"; | |
Json::Value root;// starts as "null"; will contain the root value after parsing | |
Json::Reader reader; | |
reader.parse(raw, root, false); | |
int test_a = root["test"].asInt(); | |
DEBUG_TOKEN(test_a); | |
// Get the value of the member of root named 'my-encoding', return 'UTF-32' if there is no | |
// such member. | |
std::string const my_encoding = root.get("my-encoding", "UTF-32").asString(); | |
// Get the value of the member of root named 'my-plug-ins'; return a 'null' value ib | |
// there is no such member. | |
const Json::Value my_plugins = root["my-plug-ins"]; | |
for (const auto &my_plugin : my_plugins)// Iterates over the sequence elements. | |
std::string const temp_str = my_plugin.asString(); | |
int const a = root["my-indent"].get("length", 3).asInt(); | |
bool const b = root["my-indent"].get("use_space", true).asBool(); | |
// ... | |
// At application shutdown to make the new configuration document: | |
// Since Json::Value has implicit constructor for all value types, it is not | |
// necessary to explicitly construct the Json::Value object: | |
root["encoding"] = "utf8"; | |
root["indent"]["length"] = 10; | |
root["indent"]["use_space"] = true; | |
int test_int = root["indent"]["lngth"].asInt(); | |
std::cout << "test_int: " << test_int << "\n"; | |
// Make a new JSON document with the new configuration. Preserve original comments. | |
std::cout << root << "\n"; | |
// For convenience, use `writeString()` with a specialized builder. | |
Json::StreamWriterBuilder wbuilder; | |
wbuilder["indentation"] = ""; | |
std::string const document = Json::FastWriter().write(root); | |
std::cout << "res: " << document << "\n"; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment