本文主要介绍使用JsonCpp库编写JSON解析程序的方法。

1 概述

JsonCpp是一个可以与JSON进行交互的C++库。官网定义如下:

jsoncpp is an implementation of a JSON reader and writer in C++.

通过使用JsonCpp,我们可以对JSON进行读写。

2 示例代码

2.1 从字符串中解析JSON

从字符串中解析JSON的示例代码(jsonstrparse.cpp),内容如下:

#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>

using namespace std;

int main()
{
    string strJsonContent = "{\"role_id\": 1,\"occupation\": \"paladin\",\"camp\": \"alliance\"}";

    int nRoleDd = 0;
    string strOccupation = "";
    string strCamp = "";
    
    Json::Reader reader;
    Json::Value 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++ -o jsonstrparse jsonstrparse.cpp -ljsoncpp

运行编译生成的程序,结果如下:

根据上述结果可知,我们成功地解析了字符串中的JSON数据。

2.2 从字符串中解析带有数组的JSON

示例代码(json_parse_array.cpp)如下:

#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>

using namespace std;

int main()
{
    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())
        {
            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数据。

3 使用说明

3.1 编译错误

在上面的源码中,引用“json.h”时使用了如下语句:

#include <jsoncpp/json/json.h>

这里如果使用如下语句替换上面的include语句(当然需要同步修改头文件目录),如下:

#include "json.h"

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

/usr/include/bits/sched.h:132:20: error: missing binary operator before token "("
 # if __GNUC_PREREQ (2, 91)
                    ^

出现上述编译错误的原因是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”中的一些宏定义缺失(如上面的编译错误),进而导致编译失败。

此问题的解决方案也很简单,就是按照我们提供的示例代码,不直接包含“json.h”,而使用间接包含,如:

#include "jsoncpp/json/json.h"

#include "json/json.h"

均可(注意同步修改头文件路径)。

GitHub 加速计划 / js / json
41.72 K
6.61 K
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:1 个月前 )
960b763e 2 个月前
8c391e04 5 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐