Json CPP 中文支持与入门示例

时间:2022-02-06 16:54:34

在每一个Json Cpp自带*.cpp文件头加上:

#include "stdafx.h"

将Json Cpp对自带的头文件的引用修改为单引号方式,例如json_reader.cpp原始代码为:

 #include <json/reader.h>
#include <json/value.h>
#include <utility>
#include <cstdio>
#include <cassert>
#include <cstring>
#include <iostream>
#include <stdexcept>

修改后(注意我引用路径的不同):

 #include "stdafx.h"
#include "reader.h"
#include "value.h"
#include <utility>
#include <cstdio>
#include <cassert>
#include <cstring>
#include <iostream>
#include <stdexcept>

定位到json_reader.cpp第87行,将代码修改为如下:

else if (cp <= 0xFFFF)
{
// add by sam BEGIN
if((cp>=0x4E00 && cp<=0x9FA5)||(cp>0x9F00 && cp<0xFA2D))
{
wchar_t src[]={};
char dest[]={};
src[]=static_cast<wchar_t>(cp);
std::string curLocale=setlocale(LC_ALL,NULL);
setlocale(LC_ALL,"chs");
wcstombs_s(NULL,dest,,src,);
result = dest;
setlocale(LC_ALL,curLocale.c_str());
}
else
{
result.resize();
result[] = static_cast<char>(0x80 | (0x3f & cp));
result[] = 0x80 | static_cast<char>((0x3f & (cp >> )));
result[] = 0xE0 | static_cast<char>((0xf & (cp >> )));
}
// add by sam END
}

使用JsonCpp例子:

JSON代码如下

 {
"function":"add",
"host":"localhost",
"port":8080,
"method":"doUserAdd",
"varname":"UserName"
"varvalue":"麦兜"
}

C++代码如下

 #include <string>
#include "Json.h"
...
using namespace std;
...
string strHost = root["host"].asString();
int strPort = root["port"].asInt();
string strMethod = root["method"].asString();
string strFunc = root["function"].asString();
string strVarName = root["varname"].asString();
string strVarValue = root["varvalue"].asString();