jsoncpp学习

1.环境配置 

C++ 操作 (读写)json 文件及jsoncpp的配置-CSDN博客

一步步跟下来,就可以了!!!

2.遇到的问题:

读取json文件,出现中文乱码!!!

参考:C++ ifstream open 读取txt/json文件出现中文乱码的解决问题-CSDN博客

这篇文章讲的很好!真心建议学习!!!

(1)ANSI编码的txt文件的读取。没有乱码

(2)转存为UTF-8的txt文件的读取,出现中文乱码

这时候需要进行一些处理!!!(相关代码看上面这篇文章的即可)

3.示例:正确读取含有中文的json文件

demo.json

 jsoncpp学习_第1张图片

代码:

// json.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。

#include 
#include 
#include "json.h"
#include "direct.h"
#include 
#include 
#include 
using namespace std;
string UTF8ToGB(const char* str)
{
	string result;
	WCHAR* strSrc;
	LPSTR szRes;

	//获得临时变量的大小
	int i = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
	strSrc = new WCHAR[i + 1];
	MultiByteToWideChar(CP_UTF8, 0, str, -1, strSrc, i);

	//获得临时变量的大小
	i = WideCharToMultiByte(CP_ACP, 0, strSrc, -1, NULL, 0, NULL, NULL);
	szRes = new CHAR[i + 1];
	WideCharToMultiByte(CP_ACP, 0, strSrc, -1, szRes, i, NULL, NULL);

	result = szRes;
	delete[]strSrc;
	delete[]szRes;

	return result;
}

std::string readFile(std::string file)
{
	std::ifstream infile;
	infile.open(file.data());   //将文件流对象与文件连接起来 
	assert(infile.is_open());   //若失败,则输出错误消息,并终止程序运行 

	string s; string strAllLine;
	while (getline(infile, s)) {
		string line = UTF8ToGB(s.c_str()).c_str();
		strAllLine += line;
	}
	infile.close();             //关闭文件输入流 
	return strAllLine;
}
void readStrJson()
{
	string str = readFile("./demo.json");
	cout << str << '\n';
	//声明类的对象
	Json::Reader reader;
	Json::Value root;

	//从字符串中读取数据  
	if (reader.parse(str, root))
	{
		std::string name = root["name"].asString();
		cout << name << endl;
	}
}

int main()
{
	readStrJson();
	system("pause");
}

输出结果:

你可能感兴趣的:(学习)