linux下jsoncpp的使用

第一步:
首先安装jsoncpp库
我买的腾讯的云服务器,系统是centos7
下边为安装指令
yum install jsoncpp-devel
安装后,我们只需要在程序中包含头文件
#include<jsoncpp/json/json.h>
就可以使用jsoncpp提供的方法去读写json文件
下边是一些常间的例子
比如对于这个test.json文件内容
{
“name” : “xiaohua”,
“age” : 18,
“sex” : “male”
}
读取的方法为
test.cpp:
#include
#include
#include<jsoncpp/json/json.h>
using namespace std;
void test()
{
Json::Value root;//内容
Json::Reader reader;//方式为读方式
ifstream in(“test.json”,ios::binary);
reader.parse(in,root);
cout << root[“name”] .asString()<< endl;
cout << root[“age”].asInt()<<endl;
cout << root[“sex”].asString() <<endl;
in.close();
}
int main()
{
test();
retrun 0;
}
我这里没有写一些判断文件是否打开的一些代码,你可以加上
然后g++ -std=c++11 -ljsoncpp test.cpp
可以得到:
xiaohua
18
male
写入的方法为
#include
#include
#include<jsoncpp/json/json.h>
using namespace std;
void test()
{
Json::Value root;//内容
root[“name”] = “lihua”;
root[“age”] = 18;
root[“sex”] = “male”;
Json::StyledWriter writer;//为格式写
//Json::FastWirter swriter;//为快速写,建议用上面,看着舒服
string res = writer.write(root);
ofstream ofs;
ofs.open(“test.json”);
ofs << str;
ofs.close();
}
int main()
{
test();
retrun 0;
}
这样就把上面的内容写入了一个名为test.json 的空文件中
类似的,你可以创建读取或者写入很多个人的信息
比如
[
{
“name” : “lihua”,
“age” : 18,
“sex” : “male”
}
{
“name” : “wangfang”,
“age” : 19,
“sex” : “female”
}
]
读取方法为
void test()
{
Json::Value root;//内容
Json::Reader reader;//方式为读方式
ifstream in(“test.json”,ios::binary);
reader.parse(in,root);
for(int i=0;i<root.size();i++)
{
cout << root[i][“name”] .asString()<< endl;
cout << root[i][“age”].asInt()<<endl;
cout << root[i][“sex”].asString() <<endl;
}
in.close();
}
int main()
{
test();
retrun 0;
}
就可以得到如下内容
lihua,
18,
male
“wangfang”,
19,
female
写方法类似

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值