【拿走主义】CJSON 解析数组详解

CJSON 下载地址以及介绍:http://sourceforge.net/projects/cjson/

bool ParseResourceString(CString StrRes,std::vector<std::string>& VecImgUrl,\
                                          std::string& VideoUrl)
{
    cJSON* JsonObj=cJSON_Parse(StrRes);

    if (!JsonObj)
    {
        CString info;
        info.Format("Json Error before: [%s]",cJSON_GetErrorPtr());
        HT_DebugOutCString(info);
        return false;
    }

    if (cJSON_Array != JsonObj->type)
    {
        HT_DebugOutCString(CString("CJSON NOT AN Array"));
        return false;
    }

    int size = cJSON_GetArraySize(JsonObj);

    for (int index = 0; index < size; index++)
    {
        cJSON* item = cJSON_GetArrayItem(JsonObj,index);

        if (NULL == item)
        {
            HT_DebugOutCString(CString("CJson item null"));
            return false;
        }

        if (cJSON_Object != item->type )
        {
            HT_DebugOutCString(CString("CJson SubArray NOT AN Object"));
            return false;
        }

        cJSON* JsonSubArrayContent = item->child;

        // GetVideoUrl
        if (std::string(JsonSubArrayContent->valuestring) == "video" \
            && VideoUrl.empty() && JsonSubArrayContent->next && \
            std::string(JsonSubArrayContent->next->string) == "url")
        {
            VideoUrl = JsonSubArrayContent->next->valuestring;
        }

        // GetPhotoUrl
        if (std::string(JsonSubArrayContent->valuestring) == "photo" \
            && JsonSubArrayContent->next && VecImgUrl.size() < MAX_PHOTO_NUM && \
            std::string(JsonSubArrayContent->next->string) == "url")
        {
            VecImgUrl.push_back(std::string(JsonSubArrayContent->next->valuestring));
        }
    }

    return true;
}


测试:

    CString test = "[{\"type\":\"video\",\"url\":\"/image/vrb2/i2/bad758759ddd47f89841366fcd02ee82/00028?key=7155&offset=2721385644&high=9744\"},\
                   {\"type\":\"photo\",\"url\":\"/image/vrb2/i2/bad758759ddd47f89841366fcd02ee82/00028?key=7152&offset=2721368861&high=8823\"},\"url\":\"/image/vrb2/i2/bad758759ddd47f89841366fcd02ee82/00028?key=714f&offset=2721135445&high=8696\"},\"url\":\"/image/vrb2/i2/bad758759ddd47f89841366fcd02ee82/00028?key=714e&offset=2721125841&high=9524\"}]";

相关文章

AJAX是一种基于JavaScript和XML的技术,能够使网页实现异步交...
在网页开发中,我们常常需要通过Ajax从后端获取数据并在页面...
在前端开发中,经常需要循环JSON对象数组进行数据操作。使用...
AJAX(Asynchronous JavaScript and XML)是一种用于创建 We...
AJAX技术被广泛应用于现代Web开发,它可以在无需重新加载页面...
Ajax是一种通过JavaScript和HTTP请求交互的技术,可以实现无...