MFC里面解析json文件格式


CString   strTemp;

//CString ->string;

string      stringMsg = (LPCSTR)(CStringA)strTemp;

//string -> CString

strTemp= stringMsg.c_str();

 原本是想接入jsonCPP,不過多線程調試一直不兼容,修改 MDd,MTd還是沒有什么用;后來想了想,干脆自己寫個;

思路:用字典解決;

void CDlg::SetMap(CMap<CString, LPCTSTR, CString, LPCTSTR> &mapContent,CString msgJson) {
	CStringArray strArray;
	CString strTemp = msgJson;
	string stringMsg = (LPCSTR)(CStringA)strTemp;

	strTemp.Remove('"');
	strTemp.Remove('{');
	strTemp.Remove('}');
	int strTempLength = strTemp.GetLength();
	
	int index = 0;
	while(true){
		index = strTemp.Find(',');
		if (-1 == index) {
			strArray.Add(strTemp);
			break;
		}
		strArray.Add(strTemp.Left(index));
		strTemp = strTemp.Right(strTemp.GetLength() - index - 1);
	}
	int length = strArray.GetSize();
	CString strMap;
	int subIndex = 0;
	CString strKey("");
	CString strValue("");
	for (int i = 0; i < length; i++) {
		strMap = strArray.GetAt(i);
		subIndex = strMap.Find(':');
		strKey = strMap.Left(subIndex);
		strValue = strMap.Right(strMap.GetLength() - subIndex - 1);
		mapContent.SetAt(strKey, strValue);
	}
}

  

void CDlg::MsgJson(CString msgJson) 
{
    CMap<CString, LPCTSTR, CString, LPCTSTR> my_Map;
    SetMap(my_Map, msgJson);
    CString pLook;
    my_Map.Lookup(L"type", pLook);
};

這樣就可以解析簡單的json.如果有多層,那么就首先通過尋找 {},進行數據分割,原理大同小異;

 


免責聲明!

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



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