(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一样也是一 ...
随机推荐
- c# 三步递交模式调用同一个存储过程
主要用于批量的sql操作:第一步创建中间表,第二步多次写数据到中间表,第三步 提交执行 创建三步递交的存储过程: CREATE PROC usp_testsbdj@bz int=0,@name VAR ...
- c# http Post Get 方法
/// <summary> /// get方式访问webapi /// </summary> /// <param name="url">< ...
- .Net Mvc过滤器观察者模式记录网站报错信息
基本介绍: 观察者模式是一种对象行为模式.它定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新.在观察者模式中,主题是通知的发布者,它发出通知时并不 ...
- PostgreSQL入门教程(命令行)
初次安装完成后 1.默认生成一个名为postgres的数据库 2.一个名为postgres的数据库用户 3.这里需要注意的是,同时还生成了一个名为postgres的Linux系统用户. 下面,我们使用 ...
- .NET Core下操作Git,自动提交代码到 GitHub
.NET Core 3.0 预览版发布已经好些时日了,博客园也已将其用于生产环境中,可见 .NET Core 日趋成熟 回归正题,你想盖大楼吗?想 GitHub 首页一片绿吗?今天拿她玩玩自动化提交代 ...
- JDK1.6 对 synchronized 的锁优化
1. 背景 在 JDK 1.6 中对锁的实现引入了大量的优化. 目的 减少锁操作的开销. 2. 锁优化 在看下面的内容之间,希望大家对 Mark Word 有个大体的理解.Java 中一个对象在堆中的 ...
- RestTemplate最详解
目录 1. RestTemplate简单使用 2. 一些其他设置 3. 简单总结 在项目中,当我们需要远程调用一个HTTP接口时,我们经常会用到RestTemplate这个类.这个类是Spring框架 ...
- python实例:利用jieba库,分析统计金庸名著《倚天屠龙记》中人物名出现次数并排序
本实例主要用到python的jieba库 首先当然是安装pip install jieba 这里比较关键的是如下几个步骤: 加载文本,分析文本 txt=open("C:\\Users\\Be ...
- pt-online-schema-change使用详解
一.pt-online介绍 pt-online-schema-change是percona公司开发的一个工具,在percona-toolkit包里面可以找到这个功能,它可以在线修改表结构 原理: 首先 ...
- Leetcode之深度优先搜索(DFS)专题-130. 被围绕的区域(Surrounded Regions)
Leetcode之深度优先搜索(DFS)专题-130. 被围绕的区域(Surrounded Regions) 深度优先搜索的解题详细介绍,点击 给定一个二维的矩阵,包含 'X' 和 'O'(字母 O) ...