cJson解析数组

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());
            }
        }
    }
}

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值