jsoncpp 解码编码 中文为空 乱码问题

在此,仅对本身出现的问题作个总结,没想到能帮到你们。php

本地C++桌面程序,用jsoncpp 对json和服务端进行通讯,静态库编译不能用,故采用的源码拷贝进行调用json

服务端 用php和客户端进行通讯服务器

服务端json 解码和编码的两个函数 json_encode json_decode  编辑器

若是使用在使用json_encode的中的字符串中有中文的话,有可能会出现,编码后,字符串为空,ide

这个我遇到的一个缘由是 php脚本文件的类型是ansi 而不是utf8 ,因此用txt文本编辑器,将脚本另存为 utf8便可,若是没有解决问题,只能绕道找找别的缘由和方法了。函数

 

 

再说说客户端C++桌面应用程序,使用jsoncpp 和服务器通讯,上传json数据的时候,json的中文老是会不对,要么乱码,要么没有值。工具

好像之前看过哪篇文章,记不清了,在这里提一句,对不对看各位的理解,错了,请指出,或者不会产生误导就行。说是jsoncpp 只支持ansi编码的字符串数据格式编码

多是让我瞎猫碰到死耗子了吧,折腾了一个多小时的问题,用这个办法解决了。spa

 

本人的编译环境vs2015 win7  平台编码字符集为unicode code

用jsoncpp 编码上传老是出错,用工具函数UnicodeToANSI一转,再传输,就没有问题了。下面贴一下,经常使用的几个工具函数,建议封装成一个工具类,函数声明为静态函数,经过类名::函数名直接调用便可

#include "cutil.h" #include <Windows.h> wstring CUtil::UTF8ToUnicode(const string& str) { int  len = 0; len = str.length(); int  unicodeLen = ::MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0); wchar_t * pUnicode; pUnicode = new  wchar_t[unicodeLen + 1]; memset(pUnicode, 0, (unicodeLen + 1)*sizeof(wchar_t)); ::MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, (LPWSTR)pUnicode, unicodeLen); wstring rt; rt = (wchar_t*)pUnicode; delete pUnicode; return rt; } string CUtil::UnicodeToUTF8(const wstring& str) { char* pElementText; int iTextLen; // wide char to multi char
    iTextLen = WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, NULL, 0, NULL, NULL); pElementText = new char[iTextLen + 1]; memset((void*)pElementText, 0, sizeof(char) * (iTextLen + 1)); ::WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, pElementText, iTextLen, NULL, NULL); string strText; strText = pElementText; delete[] pElementText; return strText; } wstring CUtil::ANSIToUnicode(const string& str) { int len = 0; len = str.length(); int unicodeLen = ::MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0); wchar_t * pUnicode; pUnicode = new wchar_t[unicodeLen + 1]; memset(pUnicode, 0, (unicodeLen + 1)*sizeof(wchar_t)); ::MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, (LPWSTR)pUnicode, unicodeLen); wstring rt; rt = (wchar_t*)pUnicode; delete pUnicode; return rt; } string CUtil::UnicodeToANSI(const wstring& str) { char* pElementText; int iTextLen; // wide char to multi char
    iTextLen = WideCharToMultiByte(CP_ACP, 0, str.c_str(), -1, NULL, 0, NULL, NULL); pElementText = new char[iTextLen + 1]; memset((void*)pElementText, 0, sizeof(char) * (iTextLen + 1)); ::WideCharToMultiByte(CP_ACP, 0, str.c_str(), -1, pElementText, iTextLen, NULL, NULL); string strText; strText = pElementText; delete[] pElementText; return strText; }

 

代码中调用

 

 

string str = CUtil::UnicodeToANSI(client->GetName().GetBuffer(0));

login["name"] = str;

 

到此,个人问题解决了,欢迎留言探讨,总有不一样的问题,也总有不一样的方法应对。

本人较懒,对原理的东西弄得有些含糊。

 

惟有下的苦功,才可习得真功啊!

相关文章
相关标签/搜索