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

代码:

cpp 复制代码
// 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");
}

输出结果:

相关推荐
西岸行者4 天前
学习笔记:SKILLS 能帮助更好的vibe coding
笔记·学习
悠哉悠哉愿意4 天前
【单片机学习笔记】串口、超声波、NE555的同时使用
笔记·单片机·学习
别催小唐敲代码4 天前
嵌入式学习路线
学习
毛小茛4 天前
计算机系统概论——校验码
学习
babe小鑫4 天前
大专经济信息管理专业学习数据分析的必要性
学习·数据挖掘·数据分析
winfreedoms4 天前
ROS2知识大白话
笔记·学习·ros2
在这habit之下4 天前
Linux Virtual Server(LVS)学习总结
linux·学习·lvs
我想我不够好。4 天前
2026.2.25监控学习
学习
im_AMBER4 天前
Leetcode 127 删除有序数组中的重复项 | 删除有序数组中的重复项 II
数据结构·学习·算法·leetcode
CodeJourney_J4 天前
从“Hello World“ 开始 C++
c语言·c++·学习