使用JsonCpp实现JSON解析的方法

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

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

  • 15
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
在 C 语言中,可以使用第三方库 cJSON 进行 JSON 解析。cJSON 是一个轻量级的、适用于嵌入式设备的 JSON 解析器,可以方便地解析 JSON 字符串并以 C 语言的数据结构进行访问。 使用 cJSON 解析 JSON 的一般步骤如下: 1. 调用 cJSON_Parse 函数解析 JSON 字符串,返回 cJSON 结构体指针。 2. 使用 cJSON_GetObjectItem 函数获取 cJSON 结构体中的子项。 3. 根据子项的类型使用对应的 cJSON_GetXxx 函数获取子项的值。 4. 使用 cJSON_Delete 函数释放 cJSON 结构体。 下面是一个简单的使用 cJSON 解析 JSON 字符串的例子: ```c #include <stdio.h> #include <stdlib.h> #include "cJSON.h" int main() { char *json_str = "{\"name\":\"Tom\",\"age\":20,\"scores\":[80,90,85]}"; cJSON *root = cJSON_Parse(json_str); if (root == NULL) { printf("JSON parse error!\n"); return -1; } cJSON *name = cJSON_GetObjectItem(root, "name"); if (name != NULL) { printf("name: %s\n", name->valuestring); } cJSON *age = cJSON_GetObjectItem(root, "age"); if (age != NULL) { printf("age: %d\n", age->valueint); } cJSON *scores = cJSON_GetObjectItem(root, "scores"); if (scores != NULL && cJSON_IsArray(scores)) { int i; for (i = 0; i < cJSON_GetArraySize(scores); i++) { cJSON *score = cJSON_GetArrayItem(scores, i); if (score != NULL) { printf("score[%d]: %d\n", i, score->valueint); } } } cJSON_Delete(root); return 0; } ``` 输出结果为: ``` name: Tom age: 20 score[0]: 80 score[1]: 90 score[2]: 85 ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

liitdar

赠人玫瑰,手有余香,君与吾共勉

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值