在ubuntu上使用jsoncpp

jsoncpp属于第三方库,c++本身不自带处理json数据的库

1.下载jsoncpp

jsoncpp的github官网下载zip包(本人下载的是jsoncpp-1.9.5.zip

2. 解压zip

把zip文件放到某个目录下(可以自己新建一个目录,比如jsoncpp)
使用unzip 解压

cd jsoncpp
unzip jsoncpp-1.9.5.zip

3.安装jsoncpp库

cd jsoncpp-1.9.5
mkdir build && cd build
cmake .. -DCMAKE_BUILD_TYPE=debug -DJSONCPP_LIB_BUILD_STATIC=ON
make
sudo make install

安装成功后可以在以下路径中查看到libjsoncpp.a文件

~/jsoncpp/jsoncpp-1.9.5/build/lib

4. 使用jsoncpp

添加头文件

#include <iostream>
#include <json/json.h>
using namespace std;

也可以使用下面的json.h

#include <jsoncpp/json/json.h>

使用示例:

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

using namespace std;

int main()
{
    
    string jsonString = "{\"name\":\"aaa\",\"age\":18}";
   cout << jsonString << endl;
   Json::Reader reader;
   Json::Value value;
    
    if (reader.parse(jsonString, value)) {
        string name = value["name"].asString();
        int age = value["age"].asInt();
        cout << name << " : " << age << endl;
    } else {
        cout << "parse error!" << endl;
    }
    return 0;
}

如果直接使用g++ xxx.cpp编译会报错

undefined reference to `Json::Reader::Reader()'

所以编译的时候要指定连接的库, 使用 -l 参数

-L(大L):指定库文件(动态库为.so文件,静态库为.a文件)所在的目录
-l(小L):指定具体的库文件

正确的编译命令为:

g++ xxx.cpp -l jsoncpp

得到a.out执行文件
运行out文件得到处理结果

./a.out
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值