jsoncpp 解碼編碼 中文為空 亂碼問題


在此,僅對自己出現的問題做個總結,沒想到能幫到大家。

本地C++桌面程序,用jsoncpp 對json和服務端進行通信,靜態庫編譯不能用,故采用的源碼拷貝進行調用

服務端 用php和客戶端進行通信

服務端json 解碼和編碼的兩個函數 json_encode json_decode  

如果使用在使用json_encode的中的字符串中有中文的話,有可能會出現,編碼后,字符串為空,

這個我遇到的一個原因是 php腳本文件的類型是ansi 而不是utf8 ,所以用txt文本編輯器,將腳本另存為 utf8即可,如果沒有解決問題,只能繞道找找別的原因和方法了。

 

 

再說說客戶端C++桌面應用程序,使用jsoncpp 和服務器通信,上傳json數據的時候,json的中文總是會不對,要么亂碼,要么沒有值。

好像以前看過哪篇文章,記不清了,在這里提一句,對不對看各位的理解,錯了,請指出,或者不會產生誤導就行。說是jsoncpp 只支持ansi編碼的字符串數據格式

可能是讓我瞎貓碰到死耗子了吧,折騰了一個多小時的問題,用這個辦法解決了。

 

本人的編譯環境vs2015 win7  平台編碼字符集為unicode 

用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;

 

到此,我的問題解決了,歡迎留言探討,總有不同的問題,也總有不同的方法應對。

本人較懶,對原理的東西弄得有些含糊。

 

唯有下的苦功,才可習得真功啊!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM