nlohmann / json 使用

 

   下载地址

    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;
}
复制代码

 

  

 

posted @   SusieSnail_SUN  阅读(1658)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示