以前在cocos2d-x项目中用到json解析,集成了libjson库后发现网上提供的解析方法大多是在解析过程中取得值,并没有将解析结果有效的保存起来,于是摸索一番,把解析结果根据数据格式存到数组或字典当中。

  不敢独享,代码奉上:

using namespace std;
void JsonUtil:: parseArrJSON(JSONNODE *n,CCObject **obj)
{
    if (n == NULL)
    {
        CCLOG("Invalid JSON Node\n");
        return;
    }
    bool isAry=false;
    // Parser
    JSONNODE_ITERATOR it = json_begin(n);
    char *key=json_name(*it);
    if (strcmp(key, "")==0) {
        //是数组
        *obj=CCArray::create();
        isAry=true;
    }else{
        //是字典
        *obj=CCDictionary::create();
        isAry=false;
    }
    while (it != json_end(n)) {
        if (*it == NULL) {
            CCLOG("Invalid JSON Node\n");
            return;
        }else if(json_type(*it)==JSON_NULL){
            CCString *char_str=CCString::ccs("");
            if (isAry) {
                ((CCArray *)*obj)->addObject(char_str);
            }else{
                string key=json_name(*it);
                CC_ASSERT(!key.empty());
                ((CCDictionary *)*obj)->setObject(char_str, key);
            }
        }else if (json_type(*it) == JSON_ARRAY || json_type(*it) == JSON_NODE) {
            CCObject *tempobj=NULL;
            parseArrJSON(*it,&tempobj);
            if (isAry) {
                ((CCArray *)*obj)->addObject(tempobj);
            }else{
                string key=json_name(*it);
                CC_ASSERT(!key.empty());
                ((CCDictionary *)*obj)->setObject(tempobj, key);
            }
        }
        else if(json_type(*it)==JSON_STRING){
            json_char *value = json_as_string(*it);   
            CCString *char_str=CCString::create(value);
            if (isAry) {
                ((CCArray *)*obj)->addObject(char_str);
            }else{
                string key=json_name(*it);
                CC_ASSERT(!key.empty());
                ((CCDictionary *)*obj)->setObject(char_str, key);
            }   
            json_free(value);
        }else if(json_type(*it)==JSON_NUMBER){
            //            json_int_t value = json_as_int(*it);
            json_number value = json_as_float(*it);
            CCString *char_str=CCString::createWithFormat("%.2f",value);
            if (isAry) {
                ((CCArray *)*obj)->addObject(char_str);
            }else{
                string key=json_name(*it);
                CC_ASSERT(!key.empty());
                ((CCDictionary *)*obj)->setObject(char_str, key);
            }
        }
        ++it;
    }
}
CCObject * JsonUtil:: jsonValue(const char *_char){
    JSONNODE *an = json_parse(_char);
    CCObject *obj=NULL;
    JsonUtil::parseArrJSON(an,&obj);
    json_delete(an);
    return obj;
}
View Code

相关文章:

  • 2022-12-23
  • 2021-06-06
  • 2022-12-23
  • 2022-01-08
  • 2021-12-05
  • 2022-12-23
  • 2021-06-03
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-13
  • 2022-12-23
相关资源
相似解决方案