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

 

代码:

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

#include <iostream>
#include <fstream>
#include "json.h"
#include "direct.h"
#include <assert.h>
#include <string>
#include <Windows.h>
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");
}

输出结果:

相关推荐

  1. jsoncpp解析文件

    2024-01-16 20:58:04       36 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-16 20:58:04       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-16 20:58:04       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-16 20:58:04       82 阅读
  4. Python语言-面向对象

    2024-01-16 20:58:04       91 阅读

热门阅读

  1. Vue2:利用watch和localStorage存储数据案例

    2024-01-16 20:58:04       58 阅读
  2. JPA查询PostgreSQL行排序问题

    2024-01-16 20:58:04       50 阅读
  3. Socket-Worker模式

    2024-01-16 20:58:04       63 阅读
  4. Snakemake:初探

    2024-01-16 20:58:04       55 阅读
  5. 融优学堂-艺术史

    2024-01-16 20:58:04       38 阅读
  6. computed和watch和watchEffect 相同和不同

    2024-01-16 20:58:04       59 阅读
  7. 【速成】蓝桥杯嵌入式省一教程

    2024-01-16 20:58:04       59 阅读