BOOL EasyJson_IsApproved(CString jsonText)
{
int leftKuoHao = 0;
int rightKuoHao = 0;
int yinHao = 0;
int len = jsonText.GetLength();
char ch = 0;
for (int i=0;i<len;i++)
{
ch = jsonText.GetAt(i);
if ( ch == '{')
leftKuoHao++;
else if ( ch == '}')
rightKuoHao++;
else if ( ch == '\"')
yinHao++;
}
if ( leftKuoHao != rightKuoHao)
return FALSE;
if ( yinHao %2 !=0 )
return FALSE;
return TRUE;
}
int EasyJson_GetString(CString jsonText,CString key,CString &valueStr)
{
if ( !EasyJson_IsApproved(jsonText) )
{
return -1;
}
CString keyStr;
int startPos = 0;
int endPos = 0;
int maoHaoPos = 0;
keyStr.Format("\"%s\"",key);
int keyLen = keyStr.GetLength();
startPos = jsonText.Find(keyStr);
if ( startPos < 0 )
{
return -2;
}
maoHaoPos = jsonText.Find(":",startPos+keyLen);
if ( maoHaoPos<0 )
{
return -3;
}
startPos = jsonText.Find("\"",maoHaoPos);
if ( startPos<0)
{
return -4;
}
endPos = jsonText.Find("\"",startPos+1);
if ( endPos<0)
{
return -5;
}
valueStr = jsonText.Mid(startPos+1,endPos-startPos-1);
return 1;
}
====用例====
CString jsonText = "{\"server\":\"ALL\",\"license\":{\"device_id\":\"000000000000015a\",\"product_id\":\"0000049a\",\"auth_key\":\"90650336387976801002993705216986\"}}";
CString valueStr;
CString keyStr="product_id";
int ret = EasyJson_GetString(jsonText,keyStr,valueStr);
printf("ret=%d,key=%s,str=%s",ret,valueStr);