如何在C++中使用nlohmann JSON读取含俄文字符的JSON文件?
解决nlohmann JSON读取UTF-8俄文乱码问题
问题场景
现有UTF-8编码的JSON文件json1.json,内容如下:
{ "name": [ { "text": "Привет мир!" }, { "text": "Hello World!" } ] }
使用nlohmann JSON库读取该文件的C++代码如下:
#include <iostream> #include <fstream> #include "lib\include\nlohmann\json.hpp" using namespace std; using namespace nlohmann; int main(){ setlocale(LC_ALL, "Russian"); // 该方法无效 json massive; string tempp; fstream f; f.open("json1.json"); f >> massive; f.close(); cout << massive["name"][0]["text"].dump()<<endl; // 俄文文本 cout << massive["name"][1]["text"].dump(); // 英文文本 }
运行程序后,输出结果:
"Р?С?РёР?РчС' Р?РёС?!" "Hello World!"
英文文本显示正常,但俄文文本出现乱码,尝试setlocale(LC_ALL, "Russian")和临时字符串变量均无法解决问题。
解决方案
需要添加<locale>头文件,并为全局环境和cout设置UTF-8区域配置,修改后的代码如下:
#include <iostream> #include <fstream> #include <locale> // 新增头文件 #include "lib\include\nlohmann\json.hpp" using namespace std; using namespace nlohmann; int main(){ locale::global(std::locale{ ".UTF-8" }); // 设置全局UTF-8区域环境 cout.imbue(std::locale("ru_RU.UTF-8")); // 为cout绑定俄文UTF-8区域 json massive; fstream f; f.open("json1.json"); f >> massive; f.close(); cout << massive["name"][0]["text"].dump()<<endl; cout << massive["name"][1]["text"].dump(); }
修改后运行程序,俄文文本即可正常显示。
内容的提问来源于stack exchange,提问作者ShawaCat
相关产品推荐
相关产品推荐

