void __fastcall TForm4::Button7Click(TObject *Sender)
{
char * jsonStr = "{\"status\":0,\"result\":[{\"x\":121.72791811820493,\"y\":29.916420450267933},{\"x\":121.12791811820493,\"y\":29.346420450267933}]}";
cJSON * root = NULL;
cJSON * item = NULL;//cjson对象
root = cJSON_Parse(jsonStr);
if (!root)
{
OLETRACE("Error before: [%s]\n",cJSON_GetErrorPtr());
}
else
{
printJson(root);
}
}
void TForm4::printJson(cJSON * root)//以递归的方式打印json的最内层键值对
{
for(int i=0; i<cJSON_GetArraySize(root); i++) //遍历最外层json键值对
{
cJSON * item = cJSON_GetArrayItem(root, i);
if(cJSON_Object == item->type) //如果对应键的值仍为cJSON_Object就递归调用printJson
printJson(item);
else //值不为json对象就直接打印出键和值
{
OLETRACE("%s", item->string);
OLETRACE("%s", cJSON_Print(item));
int iCount = cJSON_GetArraySize(item);
for(int i=0 ;i < iCount;i++)
{
cJSON * pSub = cJSON_GetArrayItem(item,i);
//OLETRACE("数组里面的内容%s",cJSON_Print(pSub));
cJSON * itemx = cJSON_GetObjectItem(pSub,"x");
cJSON * itemy = cJSON_GetObjectItem(pSub,"y");
double x = itemx->valuedouble;
double y = itemy->valuedouble;
AnsiString temp;
temp.printf("x=%10.7f ,y= %9.7f ",x,y);
OLETRACE(temp.c_str());
}
}
}
}