下载地址
https://github.com/nlohmann/json/tree/develop/single_include/nlohmann/json.hpp
引入工程
json.hpp是源文件包含了所有的函数,引入头文件在 .cpp文件即可;
json.hpp 文件的目录是项目工程 include文件子目录下;
#include "include/nlohmann/json.hpp" using namespace std; using json = nlohmann::json;
编写代码时注意点:
复杂json结构通过多层json 结构嵌套,代码如下:
json j; j["name"] = "xxxx"; for (size_t i = 0; i < 3; i++) { json js; js["num"] = i; j["nums"][i] = js; }
VS 使用 json 常见问题:
中文出错;
JSON_THROW(type_error::create(316, concat("invalid UTF-8 byte at index ", std::to_string(i), ": 0x", hex_bytes(byte | 0)), nullptr));
解决办法:
使用 GbkToUtf8 对中文提前转码; (如有其他好的方法,望回复!!!)
如:
json j; // 首先创建一个空的json对象 j["name"] = GbkToUtf8("某某某") ;
转码代码如下:
string GbkToUtf8(const char* src_str) { int len = MultiByteToWideChar(CP_ACP, 0, src_str, -1, NULL, 0); wchar_t* wstr = new wchar_t[len + 1]; memset(wstr, 0, len + 1); MultiByteToWideChar(CP_ACP, 0, src_str, -1, wstr, len); len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL); char* str = new char[len + 1]; memset(str, 0, len + 1); WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL); string strTemp = str; if (wstr) delete[] wstr; if (str) delete[] str; return strTemp; } string Utf8ToGbk(const char* src_str) { int len = MultiByteToWideChar(CP_UTF8, 0, src_str, -1, NULL, 0); wchar_t* wszGBK = new wchar_t[len + 1]; memset(wszGBK, 0, len * 2 + 2); MultiByteToWideChar(CP_UTF8, 0, src_str, -1, wszGBK, len); len = WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, NULL, 0, NULL, NULL); char* szGBK = new char[len + 1]; memset(szGBK, 0, len + 1); WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, szGBK, len, NULL, NULL); string strTemp(szGBK); if (wszGBK) delete[] wszGBK; if (szGBK) delete[] szGBK; return strTemp; }
标签:CP,len,nlohmann,json,wstr,str,使用,NULL From: https://www.cnblogs.com/susiesnai-sun/p/16779631.html