加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

JsonCpp遍历json

发布时间:2020-12-16 19:34:47 所属栏目:百科 来源:网络整理
导读:转自 :http://blog.csdn.net/yuanxiaobo007/article/details/26229615 [cpp] view plain copy #include"json.h" typedef Json::WriterJsonWriter; typedef Json::ReaderJsonReader; typedef Json::ValueJsonValue; void print(JsonValuev) { JsonValue::Mem

转自 :http://blog.csdn.net/yuanxiaobo007/article/details/26229615


[cpp] view plain copy
  1. #include"json.h"
  2. typedefJson::WriterJsonWriter;
  3. typedefJson::ReaderJsonReader;
  4. typedefJson::ValueJsonValue;
  5. voidprint(JsonValuev)
  6. {
  7. JsonValue::Membersmem=v.getMemberNames();
  8. for(autoiter=mem.begin();iter!=mem.end();iter++)
  9. {
  10. cout<<*iter<<"t:";
  11. if(v[*iter].type()==Json::objectValue)
  12. cout<<endl;
  13. print(v[*iter]);
  14. }
  15. elseif(v[*iter].type()==Json::arrayValue)
  16. cout<<endl;
  17. autocnt=v[*iter].size();
  18. for(autoi=0;i<cnt;i++)
  19. print(v[*iter][i]);
  20. }
  21. if(v[*iter].type()==Json::stringValue)
  22. cout<<v[*iter].asString()<<endl;
  23. if(v[*iter].type()==Json::realValue)
  24. cout<<v[*iter].asDouble()<<endl;
  25. if(v[*iter].type()==Json::uintValue)
  26. cout<<v[*iter].asUInt()<<endl;
  27. else
  28. cout<<v[*iter].asInt()<<endl;
  29. return;
  30. }

//搜索json中指定的key的value,这是原创,哈哈

copy
    //搜索json得到指定key的值,只支持stringvalue
  1. //如果strcontent不为空,使用strcontent解析,如果为空直接使用v
  2. stringGetJsonStringValue(stringstrContent,string&strKey,Json::Valuev)
  3. if(!strContent.empty())
  4. Json::Readerreader;
  5. if(!reader.parse(strContent,v))
  6. returnstring("");
  7. Json::Value::Membersmem=v.getMemberNames();
  8. Json::Value::Members::iteratorit;
  9. //遍历所有key广度搜索
  10. for(it=mem.begin();it!=mem.end();it++)
  11. if(*it==strKey)
  12. if(v[*it].type()==Json::stringValue)
  13. returnv[*it].asString();
  14. returnstring("");
  15. //如果未找到,再深度搜索
  16. for(it=mem.begin();it!=mem.end();it++)
  17. Json::ValueTypetype=v[*it].type();
  18. if(type==Json::objectValue)
  19. stringstrvalue=GetJsonStringValue(string(""),strKey,v[*it]);
  20. if(!strvalue.empty())
  21. returnstrvalue;
  22. if(type==Json::arrayValue)
  23. for(inti=0;i<v[*it].size();i++)
  24. //如果在递归的过程中已找到,则返回
  25. stringstrvalue=GetJsonStringValue(string(""),v[*it][i]);
  26. if(!strvalue.empty())
  27. returnstrvalue;
  28. }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读