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

来源:互联网 发布:长城显示器怎么样 知乎 编辑:程序博客网 时间:2024/04/30 11:41

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\"},\                   {\"type\":\"photo\",\"url\":\"/image/vrb2/i2/bad758759ddd47f89841366fcd02ee82/00028?key=714f&offset=2721135445&high=8696\"},\                   {\"type\":\"photo\",\"url\":\"/image/vrb2/i2/bad758759ddd47f89841366fcd02ee82/00028?key=714e&offset=2721125841&high=9524\"}]";