libjansson库简单使用

本文分享了作者在使用libjansson库时的经验,通过实际代码示例详细介绍了该库的API用法,旨在为其他开发者提供参考和学习资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

网上对 libjansson 库的使用介绍较少,即使有也是简单的解析和组装jason,我通过尝试了很多次,算是把库的使用方法给试出来了,把我的代码贴处理,方便大家学习参考:
libjansson API介绍
CJsonHandle.h:

#ifndef CJSONHANDLE_H
#define CJSONHANDLE_H
#include <string>
#include <map>
#include <algorithm>
#include <jansson.h>
using namespace std;
class CJsonHandle
{
   
public:
    CJsonHandle();

public:
    //只获取第一级的值,不遍历查找
    static bool GetStringFromJson(const std::string& strKey,std::string &strValue,const std::string& strJson);//从json中获取string值
    static bool GetIntFromJson(const std::string& strKey, int& nValue,const std::string& strJson);//从json中获取int值
    static bool GetBoolFromJson(const std::string& strKey, bool& bValue,const std::string& strJson);//从json中获取bool值
    static bool GetDoubleFromJson(const std::string& strKey, double& fValue,const std::string& strJson);//从json中获取double值
    static bool GetArrayFromJson(const std::string& strKey, std::map<int, std::string> &map_ArrayJson,const std::string& strJson);//从json中获取json数组
    static bool GetJsonObjectFromJson(const std::string& strKey, std::string& strObjectValue,const std::string& strJson);//从json中获取json对象
    //将值组装为一级
    static bool EncodeIntToJson(const std::string &strKey,const int& nVaule,std::string &strJson);
    static bool EncodeDoubleToJson(const std::string& strKey,const double& fVaule,std::string &strJson);//存在精度问题
    static bool EncodeBoolToJson(const std::string& strKey,const bool& bVaule,std::string &strJson);
    static bool EncodeStringToJson(const std::string& strKey,const std::string& strVaule,std::string &strJson);

    static bool EncodeArrayToJson(const std::string& strNode,const std::string& strValue,std::string &strJson);
    static bool EncodeObjectToJson(const std::string& strNode,const std::string& strValue,std::string &strJson);
};

#endif // CJSONHANDLE_H

CJsonHandle.cpp:

#include "cjsonhandle.h"

void print_json(json_t* pObj)
{
   
    char *pJson = json_dumps( pObj ,JSON_COMPACT);
    if(pJson)
    {
   
        string strJson = pJson;
        printf("strJson:%s\n",strJson.data());
        free(pJson);
    }
}

CJsonHandle::CJsonHandle()
{
   
}

bool CJsonHandle::GetStringFromJson(const std::string& strKey,std::string &strValue,const std::string& strJson)
{
   
    if(strKey.empty()==true)
        return false;
    json_t* root;
    json_error_t err;
    root = json_loads(strJson.data(),0,&err);//JSON_DISABLE_EOF_CHECK 模式会将错误jason格式解析
    if(!root)
    {
   
        return false;
    }
    json_t *object;
    object = json_object_get(root,strKey.data());
    if(object)
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值