jsoncpp的读写操作

前端之家收集整理的这篇文章主要介绍了jsoncpp的读写操作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

代码如下

#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;
}
原文链接:https://www.f2er.com/json/289732.html

猜你在找的Json相关文章