Jsoncpp 使用方法大全

来源 http://blog.csdn.net/yc461515457/article/details/52749575

Json(JavaScript Object Notation )是一种轻量级的数据交换格式。简而言之,Json组织形式就和python中的字典, C/C++中的map一样,是通过key-value对来组织的,key是任意一个唯一字符串,value可以是bool,int,string 或者嵌套的一个json。关于Json 格式可以参考官方网站。 
Jsoncpp 是一个用来处理 Json文本的开源C++库,下面就简单介绍使用Jsoncpp对Json文件的常见操作。


Jsoncpp 常用变量介绍

在Jsoncpp中,有几个常用的变量特别重要,首先介绍一下。

Json::Value

Json::Value 用来表示Json中的任何一种value抽象数据类型,具体来说,Json中的value可以是一下数据类型:

  • 有符号整数 signed integer [range: Value::minInt - Value::maxInt]
  • 无符号整数 unsigned integer (range: 0 - Value::maxUInt)
  • 双精度浮点数 double
  • 字符串 UTF-8 string
  • 布尔型 boolean
  • 空 ‘null’
  • 一个Value的有序列表 an ordered list of Value
  • collection of name/value pairs (javascript object)

可以通过[]的方法来取值。

//Examples:
Json::Value null_value; // null
Json::Value arr_value(Json::arrayValue); // [] Json::Value obj_value(Json::objectValue); // {}

Json::Reader

Json::Reader可以通过对Json源目标进行解析,得到一个解析好了的Json::Value,通常字符串或者文件输入流可以作为源目标。

假设现在有一个example.json文件

{"encoding" : "UTF-8","plug-ins" : [ "python", "c++", "ruby" ], "indent" : { "length" : 3, "use_space": true } }

使用Json::Reader对Json文件进行解析:

bool parse (const std::string &document, Value &root, bool collectComments=true) bool parse (std::istream &is, Value &root, bool collectComments=true)

Json::Value root;
Json::Reader reader;
std::ifstream ifs("example.json");//open file example.json if(!reader.parse(ifs, root)){ // fail to parse } else{ // success std::cout<<root["encoding"].asString()<<endl; std::cout<<root["indent"]["length"].asInt()<<endl; }

使用Json::Reader对字符串进行解析

bool Json::Reader::parse ( const char * beginDoc,const char * endDoc, Value & root, bool collectComments = true )
Json::Value root;
Json::Reader reader;const char* s = "{\"uploadid\": \"UP000000\",\"code\": 100,\"msg\": \"\",\"files\": \"\"}"; if(!reader.parse(s, root)){ // "parse fail"; } else{ std::cout << root["uploadid"].asString();//print "UP000000" }

Json::Writer

Json::Writer 和 Json::Reader相反,是把Json::Value对象写到string对象中,而且Json::Writer是个抽象类,被两个子类Json::FastWriter和Json::StyledWriter继承。 
简单来说FastWriter就是无格式的写入,这样的Json看起来很乱没有格式,而StyledWriter就是带有格式的写入,看起来会比较友好。

Json::Value root;
Json::Reader reader;
Json::FastWriter fwriter; Json::StyledWriter swriter; if(! reader.parse("example.json", root)){ // parse fail return 0; } std::string str = fwriter(root); std::ofstream ofs("example_fast_writer.json"); ofs << str; ofs.close(); str = swriter(root); ofs.open("example_styled_writer.json"); ofs << str; ofs.close();

结果: 
example_styled_writer.json

{"encoding" : "UTF-8","plug-ins" : [ "python", "c++", "ruby" ], "indent" : { "length" : 3, "use_space": true } }

example_fast_writer.json

{"encoding" : "UTF-8","plug-ins" : ["python","c++","ruby"],"indent" : { "length" : 3, "use_space": true}}

Jsoncpp 其他操作

通过前面介绍的Json::value, Json::Reader, Json::Reader 可以实现对Json文件的基本操作,下面介绍一些其他的常用的操作。

判断key是否存在

bool Json::Value::isMember ( const char * key) constReturn true if the object has a member named key. Note 'key' must be null-terminated. bool Json::Value::isMember ( const std::string & key) const bool Json::Value::isMember ( const char* key, const char * end ) const
// print "encoding is a member"
if(root.isMember("encoding")){std::cout<<"encoding is a member"<<std::endl; } else{ std::cout<<"encoding is not a member"<<std::endl; } // print "encode is not a member" if(root.isMember("encode")){ std::cout<<"encode is a member"<<std::endl; } else{ std::cout<<"encode is not a member"<<std::endl; }

判断Value是否为null

首先要给example.json添加一个key-value对:

{"encoding" : "UTF-8","plug-ins" : [ "python", "c++", "ruby" ], "indent" : { "length" : 3, "use_space": true }, "tab-length":[], "tab":null }

判断是否为null的成员函数

bool Json::Value::isNull ( ) const
if(root["tab"].isNull()){std::cout << "isNull" <<std::endl;//print isNull }
if(root.isMember("tab-length")){//trueif(root["tab-length"].isNull()){ std::cout << "isNull" << std::endl; } else std::cout << "not Null"<<std::endl; // print "not Null", there is a array object([]), through this array object is empty std::cout << "empty: " << root["tab-length"].empty() << std::endl;//print empty: 1 std::cout << "size: " << root["tab-length"].size() << std::endl;//print size: 0 }

另外值得强调的是,Json::Value和C++中的map有一个共同的特点,就是当你尝试访问一个不存在的 key 时,会自动生成这样一个key-value默认为null的值对。也就是说

 root["anything-not-exist"].isNull(); //falseroot.isMember("anything-not-exist"); //true

总结就是要判断是否含有key,使用isMember成员函数,value是否为null使用isNull成员函数,value是否为空可以用empty() 和 size()成员函数。

得到所有的key

typedef std::vector<std::string> Json::Value::Members Value::Members Json::Value::getMemberNames ( ) const Return a list of the member names. If null, return an empty list. Precondition type() is objectValue or nullValue Postcondition if type() was nullValue, it remains nullValue

可以看到Json::Value::Members实际上就是一个值为string的vector,通过getMemberNames得到所有的key。

删除成员

Value Json::Value::removeMember( const char* key)   Remove and return the named member. Do nothing if it did not exist. Returns the removed Value, or null. Precondition type() is objectValue or nullValue Postcondition type() is unchanged Value Json::Value::removeMember( const std::string & key) bool Json::Value::removeMember( std::string const &key, Value *removed) Remove the named map member. Update 'removed' iff removed. Parameters key may contain embedded nulls. Returns true iff removed (no exceptions)

参考

http://open-source-parsers.github.io/jsoncpp-docs/doxygen/index.html

转载于:https://www.cnblogs.com/lsgxeva/p/8093223.html

Jsoncpp 使用方法大全相关推荐

  1. robo3t 连接服务器数据库_车牌识别软件连接各种数据库方法大全

    软件连接各种数据库方法大全 1:软件连接免安装数据库. 免安装数据库使用方便,不受操作系统版本影响,不用安装,解压打开运行即可,所以免安装数据库不要放在桌面上,也不要解压打开多个. 打开车牌识别软件, ...

  2. C语言常用排序方法大全

    C语言常用排序方法大全 /* ============================================================================= 相关知识介绍( ...

  3. python基础30个常用代码大全-Python3列表内置方法大全及示例代码小结

    Python中的列表是简直可说是有容乃大,虽然看似类似C中的数组,但是Python列表可以接受任意的对象元素,比如,字符串,数字,布尔值,甚至列表,字典等等,自由度提升到一个新的高度,而Python也 ...

  4. mysql删除重复文章标题_MySQL中查询、删除重复记录的方法大全

    前言 本文主要给大家介绍了关于MySQL中查询.删除重复记录的方法,分享出来供大家参考学习,下面来看看详细的介绍: 查找所有重复标题的记录: 一.查找重复记录 1.查找全部重复记录 2.过滤重复记录( ...

  5. IT 巡检内容、方法大全

    IT 巡检内容.方法大全 目 录 1.  概述 2.  巡检维度 3.  巡检内容 4.  巡检方法 5.  常用命令.常见问题和解决方法 6.  附录 1 词汇表 7.  附录 2 参考资料 1. ...

  6. js检测字符串方法大全

    js检测字符串方法大全 <script> /* function obj$(id)                      根据id得到对象 function val$(id)      ...

  7. java读取文件的方法是_Java读取文件方法大全

    Java读取文件方法大全 2011/11/25 9:18:42  tohsj0806  http://tohsj0806.iteye.com  我要评论(0) 摘要:文章来源:http://www.c ...

  8. SEO搜索引擎优化排名方法大全

    SEO搜索引擎优化排名方法大全 正确的搜索引擎优化可以有效的帮助网站得到正确的排名,仅此而已,这也是我写这篇文章的目的. 过度优化甚至作弊不但费时费力,而且对网站没有实际帮助. 提高在搜索引擎中排名的 ...

  9. 生成osm文件_超酷城市肌理!地理数据信息爬取方法大全(B篇)DEM+POI+OSM

    WENWEN:这一弹是对第一弹的补充和深化讲解,上一弹请点击常用的地理数据信息爬取方法大全(前期场地信息获取第一弹),关于DEM获取地形地理空间数据云提交任务一直在排队的问题,这个应该是官网的问题,不 ...

最新文章

  1. 图像处理中,SIFT,FAST,MSER,STAR等特征提取算法的比较与分析(利用openCV实现)
  2. 37. Sudoku Solver **
  3. BitNami一键安装Redmine
  4. python 计算协方差矩阵_opencv2学习:计算协方差矩阵
  5. 修改文章更新缓存php,php – 使用liipImagineBundle更新/删除记录时删除/更新缓存的图像...
  6. 云起智慧中心连接华为_华为新款鸿蒙产品企业智慧屏亮相:可连接电脑和手机多屏协同工作...
  7. cocos2d环境及创建一个自己的项目
  8. 安装多个mysql实例(debian版本)
  9. html手机弧线div,纯css实现让div的四个角成弧形
  10. 声纹识别技术的现状、局限与趋势
  11. widows 系统下调试 ios webview里的H5页面
  12. 计算机文献中的经典语录,经典文献语录摘抄
  13. 2020-09-22
  14. linphone 智能带宽分配
  15. 一种简洁的流式推送文件分享法
  16. 微信小程序多个倒计时
  17. 【单片记笔记】基于STM32F103的NEC红外发送接收使用同一个定时器的一体设计
  18. 基于springboot+mybatis+jsp日用品商城管理系统
  19. Yoga14s 2021锐龙集显版蓝牙失效问题的解决方法
  20. System.currentTimeMillis()+time*1000

热门文章

  1. 文件名lin.php是什么,Linsexu程序安装PHP详细软件教程
  2. sql 在某段时间_解Bug之路记一次中间件导致的慢SQL排查过程
  3. 人脸检测(十二)--DDFD算法
  4. 敏捷开发一千零一夜读书笔记之敏捷初探
  5. DSP之时钟与定时器之二通用定时器
  6. 连接数mysql证登录名和密码_mysql连接数
  7. 高中电子技术——二极管的类型和作用
  8. linux exec 脚本之家,详解Shell脚本中调用另一个Shell脚本的三种方式
  9. PAT (Basic Level) Practice1001 害死人不偿命的(3n+1)猜想
  10. TinyML与Tensor Flow Lite的关系