Json CPP 中文支持与入门示例
在每一个Json Cpp自带*.cpp文件头加上:
#include "stdafx.h"
将Json Cpp对自带的头文件的引用修改为单引号方式,例如json_reader.cpp原始代码为:
1 #include2 #include 3 #include 4 #include 5 #include 6 #include 7 #include 8 #include
修改后(注意我引用路径的不同):
1 #include "stdafx.h" 2 #include "reader.h" 3 #include "value.h" 4 #include5 #include 6 #include 7 #include 8 #include 9 #include
定位到json_reader.cpp第87行,将代码修改为如下:
else if (cp <= 0xFFFF) { // add by sam BEGIN if((cp>=0x4E00 && cp<=0x9FA5)||(cp>0x9F00 && cp<0xFA2D)) { wchar_t src[2]={0}; char dest[5]={0}; src[0]=static_cast(cp); std::string curLocale=setlocale(LC_ALL,NULL); setlocale(LC_ALL,"chs"); wcstombs_s(NULL,dest,5,src,2); result = dest; setlocale(LC_ALL,curLocale.c_str()); } else { result.resize(3); result[2] = static_cast<char>(0x80 | (0x3f & cp)); result[1] = 0x80 | static_cast<char>((0x3f & (cp >> 6))); result[0] = 0xE0 | static_cast<char>((0xf & (cp >> 12))); } // add by sam END }
使用JsonCpp例子:
JSON代码如下
1 { 2 "function":"add", 3 "host":"localhost", 4 "port":8080, 5 "method":"doUserAdd", 6 "varname":"UserName" 7 "varvalue":"麦兜" 8 }
C++代码如下
1 #include <string> 2 #include "Json.h" 3 ... 4 using namespace std; 5 ... 6 string strHost = root["host"].asString(); 7 int strPort = root["port"].asInt(); 8 string strMethod = root["method"].asString(); 9 string strFunc = root["function"].asString(); 10 string strVarName = root["varname"].asString(); 11 string strVarValue = root["varvalue"].asString();