Json与JsonCpp学习笔记01

mac2025-12-02  6

Json结构

json官网

{ "PluginVersion": 1.1910309, "D2Vertion": 1.10, "Introduction": "学习交流用", "AuthorInfomation" : "null", "Thanks" : "null", "Modules": [ { "Name": "Start Show", "HotKey": "VK_V", "IsOn": true, "Description": "开场显示", "InfomationArrays": [ "欢迎!!!" "欢迎2!!!" "欢迎3!!!" ] } ] }

官方的帮助的文件的地址: [http://open-source-parsers.github.io/jsoncpp-docs/doxygen/index.html#_intro]

Json使用

文件中自带的4个案例: readFromStream readFromString streamWrite stringWrite

//从String类字符串读取到root中(readFromString)

#include "json/json.h" #include <iostream> int main() { const std::string rawJson = R"({"Age": 20, "Name": "colin"})"; const int rawJsonLength = static_cast<int>(rawJson.length()); JSONCPP_STRING err; Json::Value root; Json::CharReaderBuilder builder; // const std::unique_ptr<Json::CharReader> reader(builder.newCharReader()); if (!reader->parse(rawJson.c_str(), rawJson.c_str() + rawJsonLength, &root,&err)) { std::cout << "error" << std::endl; return EXIT_FAILURE; } const std::string name = root["Name"].asString(); const int age = root["Age"].asInt(); std::cout << name << std::endl; std::cout << age << std::endl; return EXIT_SUCCESS; }

//从Stream中读取到root中(readFromStream)

// comment head { // comment before "key" : "value" // comment after }// comment tail #include "json/json.h" #include <fstream> #include <iostream> int main(int argc, char* argv[]) { Json::Value root; std::ifstream ifs; ifs.open(argv[1]); Json::CharReaderBuilder builder; builder["collectComments"] = true; JSONCPP_STRING errs; if (!parseFromStream(builder, ifs, &root, &errs)) { std::cout << errs << std::endl; return EXIT_FAILURE; } std::cout << root << std::endl; return EXIT_SUCCESS; }

//写入Stream流(streamWrite)

#include "json/json.h" #include <iostream> /** \brief Write the Value object to a stream. * Example Usage: * $g++ streamWrite.cpp -ljsoncpp -std=c++11 -o streamWrite * $./streamWrite * { * "Age" : 20, * "Name" : "robin" * } */ int main() { Json::Value root; Json::StreamWriterBuilder builder; const std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter()); root["Name"] = "robin"; root["Age"] = 20; writer->write(root, &std::cout); return EXIT_SUCCESS; }

//写入字符串(stringWrite)

#include "json/json.h" #include <iostream> /** \brief Write a Value object to a string. * Example Usage: * $g++ stringWrite.cpp -ljsoncpp -std=c++11 -o stringWrite * $./stringWrite * { * "action" : "run", * "data" : * { * "number" : 1 * } * } */ int main() { Json::Value root; Json::Value data; root["action"] = "run"; data["number"] = 1; root["data"] = data; Json::StreamWriterBuilder builder; const std::string json_file = Json::writeString(builder, root); std::cout << json_file << std::endl; return EXIT_SUCCESS; }
最新回复(0)