本文主要介绍使用JsonCpp库,通过C++编程语言编写JSON封装程序的具体方法。
1 示例程序
1.1 封装普通的JSON结构
示例代码(json_create_test1.cpp)的内容如下:
#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>
using namespace std;
int main()
{
Json::Value root;
string strJsonMsg;
// 字符串类型
root["occupation"] = "paladin";
// 布尔类型
root["valid"] = true;
// 数字类型
root["role_id"] = 1;
// 将json转换为string类型
strJsonMsg = root.toStyledString();
cout<< "strJsonMsg is: " << strJsonMsg << endl;
return 0;
}
编译并执行上述代码,运行结果如下:
从上述执行结果能够看到,上述示例程序成功地创建了一个json结构。
1.2 封装带有数组的JSON结构
示例代码(json_array_create.cpp)的内容如下:
#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>
using namespace std;
int main()
{
Json::Value root;
Json::Value ArrayObj;
Json::Value ArrayItem1;
Json::Value ArrayItem2;
string strJsonMsg;
// 1. 添加数组外数据
root["type"] = "roles_msg";
root["valid"] = true;
// 2. 编写数组内容
ArrayItem1["role_id"] = 1;
ArrayItem1["occupation"] = "paladin";
ArrayItem1["camp"] = "alliance";
ArrayObj.append(ArrayItem1);
ArrayItem2["role_id"] = 2;
ArrayItem2["occupation"] = "Mage";
ArrayItem2["camp"] = "alliance";
ArrayObj.append(ArrayItem2);
// 3. 添加数组数据
root["list"] = ArrayObj;
// 将json转换为string类型
strJsonMsg = root.toStyledString();
cout<< "strJsonMsg is: " << endl << strJsonMsg << endl;
return 0;
}
编译并执行上述代码,运行结果如下:
通过上述执行结果能够看到,上述示例程序成功地创建了一个带有数组的json结构。