jsoncpp笔记
Json
Json是一种轻量级数据交换格式,可以表示数字,字符串,布尔值,null,数组,键值对:
{
"encoding" : "UTF-8",
"plug-ins" : [
"python",
"c++",
"ruby"
],
"indent" : { "length" : 3, "use_space": true }
}
JsonCpp
JsonCpp是用C++编写的Json库,接口设计精巧易用:
# 安装步骤
wget https://github.com/open-source-parsers/jsoncpp/archive/1.8.4.tar.gz -O jsoncpp-1.8.4.tar.gz
tar -xzf jsoncpp-1.8.4.tar.gz
cd jsoncpp-1.8.4
mkdir build && cd build
cmake3 -DJSONCPP_WITH_TESTS=Off -DJSONCPP_WITH_PKGCONFIG_SUPPORT=Off -DBUILD_STATIC_LIBS=ON ..
sudo make install
使用案例
从字符串解析出Json对象
#include <iostream>
#include <string>
#include <memory>
#include <json/json.h>
int main(int argc, char const *argv[])
{
(void)argc;
(void)argv;
std::string rawJson = R"({
"encoding" : "UTF-8",
"plug-ins" : [
"python",
"c++",
"ruby"
],
"indent" : { "length" : 3, "use_space": true }
})";
Json::Value root; // 根json对象
std::string err;
Json::CharReaderBuilder builder;
std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
if (!reader->parse(rawJson.c_str(), rawJson.c_str() + rawJson.size(), &root, &err)) {
std::cout << "err:" << err << std::endl;
return 1;
}
// 对于不存在的字段,返回null json对象
if (root["nonexist"].isNull()) {
std::cout << "root[nonexist] is null" << std::endl;
}
std::string encoding = root["encoding"].asString();
std::cout << "root[encoding] is " << encoding << std::endl;
// 对于获取数组第0个元素,需要写0u,以便和NULL区别开
std::string plugin0 = root["plug-ins"][0u].asString();
std::cout << "root[plug-ins][0u] is " << plugin0 << std::endl;
// 类型不匹配抛出异常,但是对于可以转换的比如true可以转换为数字1,数字可以转换为字符串等等则进行自动转换
int n = root["plug-ins"][0u].asInt();
std::cout << n << std::endl;
return 0;
}
从输入流解析出Json对象
#include <iostream>
#include <fstream>
#include <string>
#include <json/json.h>
int main(int argc, char const *argv[])
{
(void)argc;
(void)argv;
Json::Value root;
std::ifstream ifs("tmp.json");
Json::CharReaderBuilder builder;
builder["collectComments"] = true;
std::string errs;
if (!parseFromStream(builder, ifs, &root, &errs)) {
std::cout << errs << std::endl;
return 1;
}
std::cout << root << std::endl;
return 0;
}
将json对象写入字符串
#include <iostream>
#include <string>
#include <json/json.h>
int main(int argc, char const *argv[])
{
(void)argc;
(void)argv;
Json::Value root;
Json::Value data;
root["action"] = "run";
data["number"] = 1;
root["data"] = data;
Json::StreamWriterBuilder builder;
std::string jsonStr = Json::writeString(builder, root);
std::cout << jsonStr << std::endl;
return 0;
}
写入输出流
#include <iostream>
#include <string>
#include <memory>
#include <json/json.h>
int main(int argc, char const *argv[])
{
(void)argc;
(void)argv;
Json::Value root;
Json::StreamWriterBuilder builder;
std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());
root["Name"] = "robin";
root["Age"] = 20;
writer->write(root, &std::cout);
return 0;
}