加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

jsoncpp的读写操作

发布时间:2020-12-16 19:06:31 所属栏目:百科 来源:网络整理
导读:代码如下 #include fstream#include cassert#include string#include iostream#include "json/json.h"#pragma comment(lib,"lib_json.lib")using namespace std;int main(){{//读操作[{"name" : "xiaoy","age" :17},{"name" : "xiaot","age" : 20}]ifstream

代码如下

#include <fstream>
#include <cassert>
#include <string>
#include <iostream>

#include "json/json.h"

#pragma comment(lib,"lib_json.lib")

using namespace std;

int main()
{
	{
		//读操作[{"name" : "xiaoy","age" :17},{"name" : "xiaot","age" : 20}]
		ifstream  ifs;
		ifs.open("f:test.json");
		assert(ifs.is_open());

		Json::Reader reader;
		Json::Value root;

		if (!reader.parse(ifs,root,false))
		{
			return -1;
		}

		string name;
		int age;
		int size = root.size();
		for (int i = 0; i < size; i++)
		{
			name = root[i]["name"].asString();
			age = root[i]["age"].asInt();

			cout << name << " " << age << endl;
		}
	}

	{
	//写操作[{"age":100,"name":"hello world"}]
	Json::Value root;
	Json::FastWriter writer;
	Json::Value person;

	person["name"] = "hello,world";
	person["age"] = 100;
	root.append(person);

	string json_file = writer.write(root);

	ofstream ofs;
	ofs.open("f:test.json");
	assert(ofs.is_open());

	ofs << json_file;
	}

	{
		//读操作{"name" : "小楼一夜听春雨","age" : 27}
		ifstream ifs;
		ifs.open("f:test.json");
		assert(ifs.is_open());

		Json::Reader reader;
		Json::Value root;
		if (!reader.parse(ifs,false))
		{
			return -1;
		}

		string name = root["name"].asString();
		int age = root["age"].asInt();

		cout << name << " " << age << endl;
	}
	return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读