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}}
  • 1

Jsoncpp 其他操作

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

判断key是否存在

bool Json::Value::isMember ( const char * key) const

Return 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
  • 1
if(root["tab"].isNull()){
std::cout << "isNull" <<std::endl;//print isNull
}
if(root.isMember("tab-length")){//true
if(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(); //false
root.isMember("anything-not-exist"); //true
  • 1
  • 2

总结就是要判断是否含有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

Jsoncpp 使用方法大全的更多相关文章

  1. [OC][转]UITableView属性及方法大全

    Tip: UITableView属性及方法大全  (摘录地址) p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; line-height: 14.0px; font: 1 ...

  2. JS去掉首尾空格 简单方法大全(原生正则jquery)

    JS去掉首尾空格 简单方法大全 var osfipin= ' http://www.cnblogs.com/osfipin/ '; //去除首尾空格 osfipin.replace(/(^\s*)|( ...

  3. js跳转页面方法大全

    js跳转页面方法大全<span id="tiao">3</span><a href="javascript:countDown"& ...

  4. Java获取各种常用时间方法大全

    Java获取各种常用时间方法大全 package cc.javaweb.test; Java中文网,Java获取各种时间大全 import java.text.DateFormat; import j ...

  5. 详细地jsoncpp编译方法 和 vs2010中导入第三方库的方法

    详细地jsoncpp编译方法 和 vs2010中导入第三方库的方法 一 编译链接 1 在相应官网下载jsoncpp 2 解压得到jsoncpp-src-0.5.0文件 3 打开jsoncpp-src- ...

  6. php文件上传大小限制的修改方法大全

    php文件上传大小限制的修改方法大全 基本就是修改maxsize选项,当然为了提高上传文件的成功率,还需要设置超时时间等. 文章如下: [php文件上传]php文件上传大小限制修改,phpmyadmi ...

  7. [Java]读取文件方法大全(转)

    [Java]读取文件方法大全   1.按字节读取文件内容2.按字符读取文件内容3.按行读取文件内容 4.随机读取文件内容 public class ReadFromFile {     /**     ...

  8. 网站开发进阶(二十六)js刷新页面方法大全

    js刷新页面方法大全 在项目开发过程中,需要实现刷新页面.经过学习,发现下面这条语句就可以轻松实现. location.reload(); // 刷新页面 有关刷新页面的其它方法,具体学习内容如下,有 ...

  9. JavaScript数组方法大全(推荐)

    原网址:http://www.jb51.net/article/87930.htm 数组在笔试中经常会出现的面试题,javascript中的数组与其他语言中的数组有些不同,为了方便之后数组的方法学习, ...

随机推荐

  1. (C#基础)各种加密学习

    之前,一直想对这个做一个了解,但是总是坚持不下去,很急躁.最近看了几遍文章,很有感触,于是又来重新开始学习,从最最基础的开始——正所谓“慢就是快”.心态变了,继续吧!上代码! using System ...

  2. Vue SSR的渲染性能

    一.前言 前端技术年年有新宠,Vue.js 2.0以其轻量级.渐进式.简洁的语法在MVVM框架中脱颖而出,一经推出便很受业界青睐. 为了提高首屏渲染速度 缓存+直出 是必不可少的.在Vue 1× 时代 ...

  3. java maven 安装

    1.java环境安装 maven 想要安装 Apache Maven 在Windows 系统上, 需要下载 Maven 的 zip 文件,并将其解压到你想安装的目录,并配置 Windows 环境变量. ...

  4. 吐血推荐:罗马尼亚无版权VPS服务商HostSolutions评测-绝对真实

    要放心大胆的玩 VPS,要找性价比高.信用好,服务稳定,限制少的服务商是很不容易的.这里我先点几个黑名单:第一类 HiFormance.VirMach 低价流 VPS 服务商,以低从吸引消费者.俗话说 ...

  5. MyEclipse CI 2018.9.0正式发布(附下载)

    MyEclipse线上特惠,在线立享专属折扣!火热开启中>> 此MyEclipse版本增加了对较新的Wildfly服务器的支持,修复了与PDT等第三方工具的兼容性,并在IDE中包含了许多错 ...

  6. websevice之三要素

    SOAP(Simple Object Access Protocol).WSDL(WebServicesDescriptionLanguage).UDDI(UniversalDescriptionDi ...

  7. JAVA中static什么作用?

    是静态修饰符,什么叫静态修饰符呢?大家都知道,在程序中任何变量或者代码都是在编译时由系统自动分配内存来存储的,而所谓静态就是指在编译后所分配的内存会一直存在,直到程序退出内存才会释放这个空间,也就是只 ...

  8. c++ 中 char 与 string 之间的相互转换问题

    第一部分: 将  char *    或者    char []   转换为  string 可以直接赋值,转换. 第二部分: 将   string   转换为 char *    或者    cha ...

  9. WinFrom调试时,弹出你正在调试发布的版本

    把下图这里改成DEBUG就好 还有项目属性里面也要改一下 问题解决!

  10. c++hook全局触控事件

    https://gist.github.com/vbfox/1339671 namespace BlackFox { using System; using System.ComponentModel ...