(1)jsoncpp库的使用
本节主要介绍 json是什么以及jsoncpp库的使用。
(1)JSON是什么
json 是一种轻量级的文本数据交换格式;
json 独立于语言、平台,使用java script语法来描述对象;
json 解析器和json库对多种不同语言均提供了支持;
json (JavaScript Object Notation) 指的是javascript对象表示方法.
(2)c++JSON书写范例
1.书写c++代码:
// main.cpp
#include <iostream>
#include "json/reader.h"
#include "json/value.h"
using namespace std; int main(int argc,char *argv[])
{
Json::Value person;
person["name"] = "MenAngel";
person["sex"] = "男";
person["age"] = ;
person["height"] = ;
cout<<person.toStyledString()<<endl;
return ;
}
2.头文件及库文件所在路径如下:
头文件:/data01/bm80/ob_rel/include/3rd
库文件:/data01/bm80/ob_rel/lib
库名:libjsoncppD.so
3.使用g++编译链接:
g++ main.cpp -ljsoncppD -I /data01/bm80/ob_rel/include/3rd -L /data01/bm80/ob_rel/lib -o test
4.执行结果如下:
{
"name" : "MenAngel",
"sex" : "男",
"age" : ,
"height" :
}
(3)html中使用javascript脚本创建java对象
1.书写html:
<html>
<body>
<h2>在 JavaScript 中创建 JSON 对象</h2>
<p>
Name: <span id="jname"></span><br />
sex: <span id="jage"></span><br />
age: <span id="jstreet"></span><br />
</p>
<script type="text/javascript">
var JSONObject= {
"name":"MenAngel",
"sex":"男",
"age":23};
document.getElementById("jname").innerHTML=JSONObject.name
document.getElementById("jage").innerHTML=JSONObject.sex
document.getElementById("jstreet").innerHTML=JSONObject.age
</script>
</body>
</html>
用浏览器打开结果如下:

(4)几个重要的jsoncpp的类
Json::Value 可以表示所有的类型,int、uint、string、object、array,boolean等;
Json::Reader 将json文件流或字符串解析到Json::Value, 主要函数有Parse;
Json::Writer 将Json::Value转化成字符串流,
Json::FastWriter 输出不带格式的json
Json::StyleWriter 输出带格式的json
(5)jsoncpp使用详细范例:
1.从字符串中解析json:
// main.cpp
#include "json/reader.h"
#include "json/value.h"
#include "stdlib.h"
using namespace std; int main(int argc,char *argv[])
{
//创建json value 并转化为字符串
Json::Value person;
person["name"] = "MenAngel";
person["isMarriged"] = false;
person["age"] = ;
person["height"] = "";
string strJson = person.toStyledString(); //解析字符串
Json::Reader reader;
Json::Value root;
string name;
bool isMarriged;
int age;
int height,weight;
if(reader.parse(strJson,root))
{
if(!root["name"].isNull())
name = root["name"].asString();
if(!root["isMarriged"].isNull())
isMarriged = root["isMarriged"].asBool();
if(!root["age"].isNull())
age = root["age"].asInt();
if(!root["height"].isNull())
height = atoi(root["height"].asString().c_str());
weight = root["weight"].asInt();
}
cout<<"name = " << name <<" "<< root["name"].isString() <<endl
<<"isMarriged = " << isMarriged <<" "<< root["isMarriged"].isBool() <<endl
<<"age = " << age <<" "<< root["age"].isInt() <<endl
<<"height = " << height <<" "<< root["height"].isObject() <<endl //当key不存在时,返回nullValue ,isObject() is 1
<<"height = " << height <<" "<< root["height"].isInt() <<endl
<<"height = " << height <<" "<< root["height"].isArray() <<endl
<<"height = " << height <<" "<< root["height"].isNumeric() <<endl
<<"weight = " << weight <<" "<< root["weight"].isObject() <<endl;
return ;
}

2.从文件中解析json
#include <iostream>
#include <fstream>
#include "stdlib.h"
#include "json/reader.h"
#include "json/value.h"
using namespace std; int main(int argc,char *argv[])
{
//创建json value 并转化为字符串
Json::Value person;
person["name"] = "MenAngel";
person["isMarriged"] = false;
person["age"] = ;
person["height"] = "";
string strJson = person.toStyledString(); const char * filename = "./json.txt";
//将json字符串写入文件
ofstream ofile;
ofile.open(filename);
ofile<<strJson<<endl;
ofile.flush();
ofile.close(); //从文件中解析json字符串
ifstream ifile;
ifile.open(filename,ios::binary);
Json::Reader reader;
Json::Value root;
string name;
bool isMarriged;
int age;
int height,weight;
if(reader.parse(ifile,root))
{
if(!root["name"].isNull())
name = root["name"].asString();
if(!root["isMarriged"].isNull())
isMarriged = root["isMarriged"].asBool();
if(!root["age"].isNull())
age = root["age"].asInt();
if(!root["height"].isNull())
height = atoi(root["height"].asString().c_str());
weight = root["weight"].asInt();
}
cout<<"name = " << name <<" "<< root["name"].isString() <<endl
<<"isMarriged = " << isMarriged <<" "<< root["isMarriged"].isBool() <<endl
<<"age = " << age <<" "<< root["age"].isInt() <<endl
<<"height = " << height <<" "<< root["height"].isObject() <<endl //当key不存在时,返回nullValue ,isObject() is 1
<<"height = " << height <<" "<< root["height"].isInt() <<endl
<<"height = " << height <<" "<< root["height"].isArray() <<endl
<<"height = " << height <<" "<< root["height"].isNumeric() <<endl
<<"weight = " << weight <<" "<< root["weight"].isObject() <<endl;
//remove(filename);
return ;
}
//json.txt
{
"name" : "MenAngel",
"isMarriged" : false,
"age" : ,
"height" : ""
}
3.FastWriter将一个Value对象格式化为JSON格式的字符串 (FastWriter、StyledWriter、StyledStreamWriter)
// main.cpp
#include <iostream>
#include <json/json.h>
using namespace std; int main(int argc,char *argv[])
{
Json::Value person;
person["name"] = "MenAngel";
person["sex"] = "男";
person["age"] = ;
person["height"] = ; Json::Writer *writer1 = new Json::FastWriter();
Json::Writer *writer2 = new Json::StyledWriter();
string str1 = writer1->write(person);
string str2 = writer2->write(person);
string str3 = person.toStyledString();//Json::StyledStreamWriter();
cout<<"str1 : "<<endl
<<str1<<endl;
cout<<"str2 : "<<endl
<<str2<<endl;
cout<<"str3 : "<<endl
<<str3<<endl;
cout<<"str4 : "<<endl
<<person<<endl;
return ;
}
str1 :
{"name":"MenAngel","sex":"男","age":23,"height":178} str2 :
{
"name" : "MenAngel",
"sex" : "男",
"age" : 23,
"height" : 178
} str3 :
{
"name" : "MenAngel",
"sex" : "男",
"age" : 23,
"height" : 178
} str4 : {
"name" : "MenAngel",
"sex" : "男",
"age" : 23,
"height" : 178
}
4.在JsonCpp中对Json:value对象中array、object、member、number、int的操作
// main.cpp
#include <iostream>
#include <json/json.h>
using namespace std; int main(int argc,char *argv[])
{
//构建json对象
Json::Value family;
Json::Value members;
family["family_id"] = ;
family["single_parent"] = false;
family["age"] = ;
family["money"] = 13.14;
for(int i = ;i < ; ++i)
{
Json::Value member;
member["id"] = i + ;
member["name"] = "name";
members.append(member);
}
family["members"] = members; //打印json value
string strJson = family.toStyledString();
cout<<family<<endl; //解析json value
Json::Reader reader;
Json::Value root;
if(reader.parse(strJson,root))
{
std::vector<std::string> list_strMembers;
if(!root.isNull() && root.isObject())
list_strMembers = root.getMemberNames();
for(auto str:list_strMembers)
{
if(!root.isMember(str))
continue;
cout<<str<<" : ";
if(!root[str].isNull())
{
if(root[str].isInt())
{
int tempInt = root[str].asInt();
cout<<" is Int,value = "<<tempInt<<endl;
}
if(root[str].isBool())
{
bool tempBool = root[str].asBool();
cout<<"is Bool,value = "<<tempBool<<endl;
}
if(root[str].isString())
{
string tempString = root[str].asString();
cout<<"is String,value = "<<tempString<<endl;
}
if(root[str].isObject())
{
Json::Value tempValue = root[str];
cout<<"is Object,value = "<<tempValue<<endl;
}
if(root[str].isArray())
{
Json::Value tempMember = root[str];
cout<<"is Array,size = "<<tempMember.size()<<endl;
for(int j = ;j < tempMember.size();j++)
{
Json::Value tempValue = tempMember[j];
cout<<" person "<<j+<<":"<<endl;
cout<<" id = "<<tempValue["id"];
cout<<" name = "<<tempValue["name"];
}
}
if(root[str].isNumeric() && !root[str].isBool())
{ //布尔值在使用[]获取时返回的即是整型又是数值类型,其中整型是数值类型的一种
double tempDouble = root[str].asDouble();
cout<<"is Double,value = "<<tempDouble<<endl;
}
}
}
}
//解析
return ;
}
{
"family_id" : ,
"single_parent" : false,
"age" : ,
"money" : 13.140,
"members" :
[
{
"id" : ,
"name" : "name"
},
{
"id" : ,
"name" : "name"
},
{
"id" : ,
"name" : "name"
},
{
"id" : ,
"name" : "name"
}
]
}
family_id : is Int,value =
single_parent : is Bool,value =
age : is Int,value =
money : is Double,value = 13.14
members : is Array,size =
person :
id =
name = "name"
person :
id =
name = "name"
person :
id =
name = "name"
person :
id =
name = "name"
在main.cpp中使用了c++11的特性因此编译时要进行指定 -std=c++11
g++ main.cpp -std=c++ -ljsoncppD -I /data01/bm80/ob_rel/include/3rd -L /data01/bm80/ob_rel/lib -o test
5.对json value的修改,删除
// main.cpp
#include <iostream>
#include <json/json.h>
using namespace std; int main(int argc,char *argv[])
{
//构建json对象
Json::Value family;
Json::Value members;
family["family_id"] = ;
family["single_parent"] = false;
family["age"] = ;
family["money"] = 13.14;
for(int i = ;i < ; ++i)
{
Json::Value member;
member["id"] = i + ;
member["name"] = "name";
members.append(member);
}
family["members"] = members; //打印json value
string strJsonBefore = family.toStyledString();
cout<<strJsonBefore<<endl; family.removeMember("age");
family["money"] = ;
//Json::Value tempDelete; //新版本中删除json数组中元素的方法
//family["members"].removeIndex(3,tempDelete);
string strJsonAfter = family.toStyledString();
cout<<strJsonAfter<<endl;
return ;
}
{
"family_id" : ,
"single_parent" : false,
"age" : ,
"money" : 13.140,
"members" : [
{
"id" : ,
"name" : "name"
},
{
"id" : ,
"name" : "name"
},
{
"id" : ,
"name" : "name"
},
{
"id" : ,
"name" : "name"
}
]
}
{
"family_id" : ,
"single_parent" : false,
"money" : ,
"members" : [
{
"id" : ,
"name" : "name"
},
{
"id" : ,
"name" : "name"
},
{
"id" : ,
"name" : "name"
},
{
"id" : ,
"name" : "name"
}
]
}
6.处理不合法的json字符串时
// main.cpp
#include <iostream>
#include <json/json.h>
using namespace std; int main(int argc,char *argv[])
{
string errorStrJson1 = "{\"key1\":\"value1\",\"}";
string errorStrJson2 = "1111 {}";
Json::Reader reader;
Json::Value root;
if(!reader.parse(errorStrJson1,root))
{
cout<<"errorStrJson1 parse error!"<<endl;
}
if(!reader.parse(errorStrJson2,root))
{
cout<<"errorStrJson2 parse error!"<<endl;
}else
{
cout<<"errorStrJson2 parse success!"<<endl;
//root.getMemberNames();会core掉
}
//启用严格模式,让非法的json解析时直接返回false,不自动容错。这样,在调用parse的时候就会返回false。
Json::Reader *pJsonParser = new Json::Reader(Json::Features::strictMode());
if(!pJsonParser->parse(errorStrJson1,root))
{
cout<<"errorStrJson1 parse error!"<<endl;
}
if(!pJsonParser->parse(errorStrJson2,root))
{
cout<<"errorStrJson2 parse error!"<<endl;
}else
{
cout<<"errorStrJson2 parse success!"<<endl;
//root.getMemberNames();会core掉
}
return ;
}

(1)jsoncpp库的使用的更多相关文章
- ubuntu 下使用 jsoncpp库
做项目的时候需要用c++解析json文件, 之前使用的是libjson 库, 但当g++ 开启 -std=c++11 选项时, 该库的很多功能不能用, 而且还有一些其他的问题, 不推荐使用. 后来采用 ...
- C++处理Json串——jsoncpp库
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,和xml类似,本文主要对VS2008中使用Jsoncpp解析json的方法做一下记录.Jsoncpp是个跨 ...
- 编译jsoncpp库以及要注意的问题
原创文章,转载请注明原作者与本文原始URL. 版本:jsoncpp-src-0.5.0.zip简介:jsoncpp是用cpp实现的json库,可以拼装,解析,生成json串.我们要把他编译成动态库.这 ...
- Windows10 VS2017 C++ Json解析(使用jsoncpp库)
1.项目必须是win32 2.生成的lib_json.lib放到工程目录下 3.incldue的头文件放到工程目录,然后设置工程->属性->配置属性->vc++目录->包含目录 ...
- linux::jsoncpp库
下载库:http://sourceforge.net/projects/jsoncpp/files/ tar -zxvf jsoncpp-src- -C jsoncpp () 安装 scons $ s ...
- VS 2010 编译安装 boost 库 -(和 jsoncpp 库共存)
boost库的简单应用很容易,网上有很多资料,但是,如果要json 和 boost 一起使用就会出现这样那样的问题, 有时候提示找不到 “libboost_coroutine-vc100-mt-sgd ...
- JsonCPP库使用
1.使用环境DevC++ a.建立C++工程,并添加.\JsonCPP\jsoncpp-master\jsoncpp-master\src\lib_json中源文件到工程中. b.添加头文件路径 2. ...
- C++的Json解析库:jsoncpp和boost
C++的Json解析库:jsoncpp和boost - hzyong_c的专栏 - 博客频道 - CSDN.NET C++的Json解析库:jsoncpp和boost 分类: 网络编程 开源库 201 ...
- C++的Json解析库:jsoncpp和boost(转)
原文转自 http://blog.csdn.net/hzyong_c/article/details/7163589 JSON(JavaScript Object Notation)跟xml一样也是一 ...
随机推荐
- spring cloud 断路器 Hystrix
一.微服务架构中使用断路器的原因 二.代码实现 1.在Ribbon中使用短路器 1.1.引入依赖 <dependency> <groupId>org.springframewo ...
- 基于vue手写tree插件那点事
目录 iview提供的控件 手写控件 手写控件扩展 手写控件总结 # 加入战队 微信公众号 主题 Tree树形控件在前端开发中必不可少,对于数据的展示现在网站大都采取树形展示.因为大数据全部展示出来对 ...
- Mysql高可用(HA)
MySQL特点: 1) 开放的源代码的关系型数据库 2) 适应于所有平台 3) 支持多线程,充分利用CPU资源,性能很出色 4) 价格便宜 5) 大数据库能处理5000万条记录. ACID 事务 一组 ...
- 教你用原生CSS写炫酷页面切换效果,跟第三方组件说拜拜
因为项目需要,别人想让我给他写一个个人博客,并且给了我一个其他人的网页,可以点此查看.有的同学可能说了,第三方博客框架这么多,为什么还要去手写的,你说这个有可能是没有看到打开这个博客. 样式介绍 给大 ...
- windows和linux下的本机IP的获取(亲测有效)
package com.handsight.platform.fras.util; import org.apache.log4j.Logger; import javax.servlet.http. ...
- Oracle数据库之四 简单查询
四.简单查询 简单查询的主要特征就是将一张数据表之中的全部数据行进行显示,而后可以利用 SELECT 子句来控制所需要的输出列. 4.1.基础语法 范例:查询 emp 表中的数据(全部数据查询) ...
- C/C++ 修改系统时间,导致sem_timedwait 一直阻塞的问题解决和分析
修改系统时间,导致sem_timedwait 一直阻塞的问题解决和分析 介绍 最近修复项目问题时,发现当系统时间往前修改后,会导致sem_timedwait函数一直阻塞.通过搜索了发现int sem_ ...
- Egret白鹭开发微信小游戏分享功能
今天给大家分享一下微信分享转发功能,话不多说,直接干 方法一: 1.在egret中打开Platfrom.ts文件,添加代码如下(当然,你也可以直接复制粘贴) /** * 平台数据接口. * 由于每款游 ...
- HDU 6052
题意略. 思路:我们单独考虑每种颜色的贡献,颜色c对答案的贡献 == 含有c的矩形个数,这就是在考查我们计数的能力,暴力可过. #include<bits/stdc++.h> #defin ...
- Java基础之String、StringBuffer、StringBuilder浅析
Java基础之String.StringBuffer.StringBuilder浅析 一.前言: 位于java.lang包下的String.StringBuilder.StringBuffer一般都是 ...