当前位置: 首页 > 工具软件 > CJsonObject > 使用案例 >

c++:json 库 jsoncpp & CJsonObject

司空福
2023-12-01

前言

jsoncpp 库

link

  • jsoncpp是一个可以与JSON 进行交互的C++

示例代码

link

1. 解析 json 对象

#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>
 
using namespace std;
 
int main()
{
	// 待解析的 json 字符串
    string strJsonContent = "{\"role_id\": 1,\"occupation\": \"paladin\",\"camp\": \"alliance\"}";
    
    // 待解析的结果
    int nRoleDd = 0;
    string strOccupation = "";
    string strCamp = "";
    
    // json 解析器
    Json::Reader reader;
    // json 根对象
    Json::Value root;
 
 	// 将 strJsonContent 解析到 root
    if (reader.parse(strJsonContent, root))
    {
        nRoleDd = root["role_id"].asInt();
        strOccupation = root["occupation"].asString();
        strCamp = root["camp"].asString();
    }
 
    cout << "role_id is: " << nRoleDd << endl;
    cout << "occupation is: " << strOccupation << endl;
    cout << "camp is: " << strCamp << endl;
 
    return 0;
}

编译:g++ jsonstrparse.cpp -o jsonstrparse -ljsoncpp

2. 解析带有数组的 json

#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>
 
using namespace std;
/*
{
	"list" : [
		{
			"camp" : "alliance",
			"occupation" : "paladin",
			"role_id" : 1
		},
        {
        	"camp" : "alliance",
        	"occupation" : "Mage",
			"role_id" : 2
		}
	],
	"type" : "roles_msg",
	"valid" : true
}

*/
int main()
{
	// 待解析的 json 字符串
    string strJsonContent = "{\"list\" : [{ \"camp\" : \"alliance\",\"occupation\" : \"paladin\",\"role_id\" : 1}, \
        {\"camp\" : \"alliance\",\"occupation\" : \"Mage\",\"role_id\" : 2}],\"type\" : \"roles_msg\",\"valid\" : true}";

	// 待解析的结果
    string strType;
    int nRoleDd = 0;
    string strOccupation;
    string strCamp;
    
    // 对象
    Json::Reader reader;
    Json::Value root;
 
 	// 解析
    if (reader.parse(strJsonContent, root))
    {
        // 【获取非数组内容】
        strType = root["type"].asString();
        cout << "type is: " << strType << endl;
 
        // 【获取数组内容】
        if (root["list"].isArray())
        {
        	// 数组内有几个对象(size)
            int nArraySize = root["list"].size();
            for (int i = 0; i < nArraySize; i++)
            {
                nRoleDd = root["list"][i]["role_id"].asInt();
                strOccupation = root["list"][i]["occupation"].asString();
                strCamp = root["list"][i]["camp"].asString();
 
                cout << "role_id is: " << nRoleDd << endl;
                cout << "occupation is: " << strOccupation << endl;
                cout << "camp is: " << strCamp << endl;
            }
        }
    }
        
    return 0;
}

写 json 文件

static void write_json(string f)
{
    Json::Value root;
    Json::FastWriter writer;
    Json::Value person;

    
    person["age"] = 28;
    person["name"] = "sb";
    root.append(person);

    string json_file = writer.write(root);

    ofstream ofs;
    ofs.open(f);
    assert(ofs.is_open());
    ofs << json_file;

    return;
}

注意

  • 这里如果使用:#include "json.h" 代替 #include <jsoncpp/json/json.h> & "#include<json/json.h>"(后两个均可编译过)

  • 编译时则会报错,很多错,看起来与 GLIBC 相关的,部分错误信息如下:

    出现上述编译错误的原因是 jsoncpp 提供的头文件 /usr/local/include/json/features.h 与 GLIBC 提供的头文件 /usr/include/features.h冲突,如果我们使用 #include “json.h” 形式包含 json.h,则需要把头文件包含路径设置为 /usr/local/include/json/,此时,如果代码中有地方包含了 features.h(实际上,这是个很常用的头文件,很多地方都会包含此文件),则就会使用 json 提供的 features.h 了(而不是 GLIBC 提供的那个 features.h),从而导致 GLIBC 提供的 features.h 中的一些宏定义缺失(如上面的编译错误),进而导致编译失败。

CJsonObject 库

link

  • CJsonObject 是基于 cJSON 全新开发一个 C++ 版的 JSON 库

  • CJsonObject 的最大优势是 轻量只有4个文件,拷贝到自己代码里即可,无须编译成库,且跨平台和编译器

  • 简单好用,开发效率极高,对多层嵌套json的读取和生成使用非常简单(大部分json解析库如果要访问多层嵌套json的最里层非常麻烦)。

示例代码

#include <string>
#include <iostream>
#include "../CJsonObject.hpp"

int main()
{
    int iValue;
    std::string strValue;
    neb::CJsonObject oJson("{\"refresh_interval\":60,"
                        "\"dynamic_loading\":["
                            "{"
                                "\"so_path\":\"plugins/User.so\", \"load\":false, \"version\":1,"
                                "\"cmd\":["
                                     "{\"cmd\":2001, \"class\":\"neb::CmdUserLogin\"},"
                                     "{\"cmd\":2003, \"class\":\"neb::CmdUserLogout\"}"
                                "],"
                                "\"module\":["
                                     "{\"path\":\"im/user/login\", \"class\":\"neb::ModuleLogin\"},"
                                     "{\"path\":\"im/user/logout\", \"class\":\"neb::ModuleLogout\"}"
                                "]"
                             "},"
                             "{"
                             "\"so_path\":\"plugins/ChatMsg.so\", \"load\":false, \"version\":1,"
                                 "\"cmd\":["
                                      "{\"cmd\":2001, \"class\":\"neb::CmdChat\"}"
                                 "],"
                             "\"module\":[]"
                             "}"
                        "]"
                    "}");
     std::cout << oJson.ToString() << std::endl;
     std::cout << "-------------------------------------------------------------------" << std::endl;
     std::cout << oJson["dynamic_loading"][0]["cmd"][1]("class") << std::endl;
     oJson["dynamic_loading"][0]["cmd"][0].Get("cmd", iValue);
     std::cout << "iValue = " << iValue << std::endl;
     oJson["dynamic_loading"][0]["module"][0].Get("path", strValue);
     std::cout << "strValue = " << strValue << std::endl;
     std::cout << "-------------------------------------------------------------------" << std::endl;
     oJson.AddEmptySubObject("depend");
     oJson["depend"].Add("nebula", "https://github.com/Bwar/Nebula");
     oJson["depend"].AddEmptySubArray("bootstrap");
     oJson["depend"]["bootstrap"].Add("BEACON");
     oJson["depend"]["bootstrap"].Add("LOGIC");
     oJson["depend"]["bootstrap"].Add("LOGGER");
     oJson["depend"]["bootstrap"].Add("INTERFACE");
     oJson["depend"]["bootstrap"].Add("ACCESS");
     std::cout << oJson.ToString() << std::endl;
     std::cout << "-------------------------------------------------------------------" << std::endl;
     std::cout << oJson.ToFormattedString() << std::endl;
}

结果:

[bwar@nebula demo]$ ./CJsonObjectTest
{"refresh_interval":60,"dynamic_loading":[{"so_path":"plugins/User.so","load":false,"version":1,"cmd":[{"cmd":2001,"class":"neb::CmdUserLogin"},{"cmd":2003,"class":"neb::CmdUserLogout"}],"module":[{"path":"im/user/login","class":"neb::ModuleLogin"},{"path":"im/user/logout","class":"neb::ModuleLogout"}]},{"so_path":"plugins/ChatMsg.so","load":false,"version":1,"cmd":[{"cmd":2001,"class":"neb::CmdChat"}],"module":[]}]}
-------------------------------------------------------------------
neb::CmdUserLogout
iValue = 2001
strValue = im/user/login
-------------------------------------------------------------------
{"refresh_interval":60,"dynamic_loading":[{"so_path":"plugins/User.so","load":false,"version":1,"cmd":[{"cmd":2001,"class":"neb::CmdUserLogin"},{"cmd":2003,"class":"neb::CmdUserLogout"}],"module":[{"path":"im/user/login","class":"neb::ModuleLogin"},{"path":"im/user/logout","class":"neb::ModuleLogout"}]},{"so_path":"plugins/ChatMsg.so","load":false,"version":1,"cmd":[{"cmd":2001,"class":"neb::CmdChat"}],"module":[]}],"depend":{"nebula":"https://github.com/Bwar/Nebula","bootstrap":["BEACON","LOGIC","LOGGER","INTERFACE","ACCESS"]}}
-------------------------------------------------------------------
{
    "refresh_interval": 60,
    "dynamic_loading":  [{
            "so_path":  "plugins/User.so",
            "load": false,
            "version":  1,
            "cmd":  [{
                    "cmd":  2001,
                    "class":    "neb::CmdUserLogin"
                }, {
                    "cmd":  2003,
                    "class":    "neb::CmdUserLogout"
                }],
            "module":   [{
                    "path": "im/user/login",
                    "class":    "neb::ModuleLogin"
                }, {
                    "path": "im/user/logout",
                    "class":    "neb::ModuleLogout"
                }]
        }, {
            "so_path":  "plugins/ChatMsg.so",
            "load": false,
            "version":  1,
            "cmd":  [{
                    "cmd":  2001,
                    "class":    "neb::CmdChat"
                }],
            "module":   []
        }],
    "depend":   {
        "nebula":   "https://github.com/Bwar/Nebula",
        "bootstrap":    ["BEACON", "LOGIC", "LOGGER", "INTERFACE", "ACCESS"]
    }
}
 类似资料: