JSON封装(C++)

版权声明:本文为博主原创文章,商业转载请联系作者获得授权,非商业转载请注明出处。 https://blog.csdn.net/liitdar/article/details/81669446

本文主要介绍使用 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结构。

猜你喜欢

转载自blog.csdn.net/liitdar/article/details/81669446