简单的介绍
JSON是一种轻量级的数据交换格式。它可以表示数字、字符串、有序的值序列和名称/值对的集合。
JsonCpp是一个c++库,允许对JSON值进行操作,包括对字符串进行序列化和反序列化。它还可以在非序列化/序列化步骤中保存现有的注释,使其成为存储用户输入文件的一种方便的格式。
下载
github 地址:https://github.com/open-source-parsers/jsoncpp
安装
- 解压
- cd jsoncpp-master/
- mkdir -p build/debug
- cd build/debug
- cmake -DCMAKE_BUILD_TYPE=debug -DBUILD_STATIC_LIBS=ON -DBUILD_SHARED_LIBS=OFF -DARCHIVE_INSTALL_DIR=. -G "Unix Makefiles" ../..
- make
- cd src/lib_json
- cp libjsoncpp.a /usr/lib
- cd ../../../../include
- cp -r json/ /usr/include
- 运行如下测试文件
测试文件
此文件转自https://www.cnblogs.com/fengbohello/p/4059435.html
原代码有些遗漏,不能直接运行,更改后如下:
#include <iostream>
#include <string>
#include <json/json.h>
void readJson();
void writeJson();
int main(int argc, char** argv) {
readJson();
writeJson();
return 0;
}
void readJson() {
using namespace std;
std::string strValue = "{\"name\":\"json\",\"array\":[{\"cpp\":\"jsoncpp\"},{\"java\":\"jsoninjava\"},{\"php\":\"support\"}]}";
Json::Reader reader;
Json::Value value;
if (reader.parse(strValue, value))
{
std::string out = value["name"].asString();
std::cout << out << std::endl;
const Json::Value arrayObj = value["array"];
for (unsigned int i = 0; i < arrayObj.size(); i++)
{
if (!arrayObj[i].isMember("cpp"))
continue;
out = arrayObj[i]["cpp"].asString();
std::cout << out;
if (i != (arrayObj.size() - 1))
std::cout << std::endl;
}
}
}
void writeJson() {
using namespace std;
Json::Value root;
Json::Value arrayObj;
Json::Value item;
item["cpp"] = "jsoncpp";
item["java"] = "jsoninjava";
item["php"] = "support";
arrayObj.append(item);
root["name"] = "json";
root["array"] = arrayObj;
root.toStyledString();
std::string out = root.toStyledString();
std::cout << out << std::endl;
}
编译
g++ jsonTest.cpp -o jsonTest -std=c++11 -ljsoncpp
结果
json
jsoncpp
{
"array" :
[
{
"cpp" : "jsoncpp",
"java" : "jsoninjava",
"php" : "support"
}
],
"name" : "json"
}
|