vs2015 读取json文件



#include "json\include\json.h"
#include <iostream>
#include <fstream>

#ifdef _DEBUG
#pragma comment(lib,"json/lib/lib_json_d.lib")
#else
#pragma comment(lib,"json/lib/lib_json.lib")
#endif
using namespace std;

int main(void)
{
        Json::Reader reader;
	Json::Value root;

	//从文件中读取
	ifstream is;
	is.open("PersonalInfo.json", ios::binary);

	if (reader.parse(is, root))
	{
		//读取根节点信息
		string name = root["name"].asString();
		int age = root["age"].asInt();
		string sex = root["sex"].asString();

		cout << "My name is " << name << endl;
		cout << "I'm " << age << " years old" << endl;
		cout << "I'm a " << sex << endl;

		//读取子节点信息
		string partner_name = root["partner"]["partner_name"].asString();
		int partner_age = root["partner"]["partner_age"].asInt();
		string partner_sex = root["partner"]["partner_sex"].asString();

		cout << "My partner's name is " << partner_name << endl;
		cout << partner_sex << " is "
			<< partner_age << " years old" << endl;

		//读取数组信息
		cout << "Here's my achievements:" << endl;
		int ach = root["achievement"]["数学"].asInt();
		cout << ach << '\t';
		ach = root["achievement"]["化学"].asInt();
		cout << ach << '\t';
		ach = root["achievement"]["物理"].asInt();
		cout << ach << '\t';
		ach = root["achievement"]["sss"].asInt();
		cout << "Reading Complete!" << endl;
	}

	is.close();
}

json库编译:

1、下载json源码

    https://github.com/open-source-parsers/jsoncpp

2、vs打开..\jsoncpp-master\makefiles\msvc2010下的工程,选择对应平台编译debug/release 版本,

生成的debug版本后缀加_d

3、jsondemo,代码见上

新建json目录,在目录下新建include、lib文件夹,将上面生产的

lib_json_d.lib、lib_json.lib
库放在lib下,\jsoncpp-master\include\json下的头文件拷贝到include目录下
展开阅读全文

没有更多推荐了,返回首页