jsoncpp的api简要说明
1 jsoncpp的api简要说明
1,解析(json字符串转为对象)
std::string strDataJson;
Json::Reader JReader;
Json::Value JObject;
if (!JReader.parse(strDataJson, JObject))
{
cerr << "parse json error." << endl;
return bSuccess;
}
2,读取
std::string strMsg = JRec["msg"].asString();
int nRetCode = JRec["ret"]..asInt();
Json::Value JList = JRec["data"]["list"];
int nSize = JList.size();
获取错误信息: JReader.getFormatedErrorMessages()
3,增加或修改
JRoot["stringdata"] = Json::Value("msg");
JRoot["intdata"] = Json::Value(10);
4,删除
JValue.removeMember("toberemove");
5,对象转为字符串
//输出无格式json字符串
Json::FastWriter fast_writer;
strJRecList = fast_writer.write(JRoot);
//格式化之后的json,有回车换行符
std::string strOut = JRoot.toStyledString();
#include "json/json.h"
const string fileName = "json.txt"; int main(int argc, char *argv[])
{
string line;
std::ifstream in(fileName.c_str());
if(!in)
return ; std::getline(in, line); Json::Reader reader;
Json::Value root; if(reader.parse(line, root))
cout << "suc" << endl;
else
cout << "fail" << endl; cout << root["status"].asInt() << endl;
cout << root["msg"].asString() << endl;
cout << root["forbidReason"].asString() << endl;
Json::Value root, ipPort;
string host;
unsigned int port = ; if(addrs.size() == )
root["hosts"].append(ipPort);
else
{
for(size_t i = ; i < addrs.size(); i++)
{
if(getIpAndPort(addrs[i], host, port))
{
ipPort["ip"] = host;
ipPort["port"] = port;
}
root["hosts"].append(ipPort);
}
}
http://blog.csdn.net/u014489596/article/details/44920557
son是一种数据交换格式,比较适合编写和阅读。jsoncpp是采用c++语言编写的用来处理json格式的第三包。直接来说明改如何使用它,本文是基于windows下的。
在github上下载jsoncpp的源代码包:https://github.com/open-source-parsers/jsoncpp。解压后用vs打开/makefiles/vs71/jsoncpp.sln项目,选择lib_json项目编译来生成lib文件,为了方便,debug和release都需要生成。
创建一个win32的空项目,将生成的lib文件包含,附加包含目录添加源代码中的include文件夹。后面简单说下比较常用的几种json处理方法。
解析json对象:
1.首先看看最简单的一种json格式,只有键-值的一重嵌套:
{
“id” : 123,
"name" : "wu"
}
我们直接将上面的数据初始化到到string对象中,方便解析,后面都是如此
- std::string json = "{\"id\" : 123, \"name\" : \"wu\"}";
- Json::Reader reader;
- Json::Value root;
- std::string name;
- int id = 0;
- if (reader.parse(json, root)) // reader将Json字符串解析到root,root将包含Json里所有子元素
- {
- name = root["name"].asString();
- id = root["id"].asInt();
- }
2.再看看数组的:
[ { "id" : 1, "name" : "wu"}, {"id":2, "name" : "tan"} ]
- std::string json = "[ {\"id\" : 1, \"name\" : \"wu\"}, {\"id\" : 2, \"name\" : \"tan\"} ]";
- Json::Reader reader;
- Json::Value root;
- std::string name;
- int id = 0;
- std::map<int, std::string> mapJson;
- if (reader.parse(json, root)) // reader将Json字符串解析到root,root将包含Json里所有子元素
- {
- for (int i = 0; i < root.size(); ++i)
- {
- name = root[i]["name"].asString();
- id = root[i]["id"].asInt();
- mapJson[id] = name;
- }
- }
3.如果是这样的数组:
{
“id” : [1, 2],
"name" : ["wu", "tan"]
}
- std::string json = "{\"id\" : [1, 2], \"name\" : [\"wu\", \"tan\"] } ";
- Json::Reader reader;
- Json::Value root;
- std::string name;
- int id = 0;
- if (reader.parse(json, root)) // reader将Json字符串解析到root,root将包含Json里所有子元素
- {
- for (int i = 0; i < root["id"].size(); ++i)
- {
- id = root["id"][i].asInt();
- }
- for (int i = 0; i < root["name"].size(); ++i)
- {
- name = root["name"][i].asString();
- }
- }
这种情况其实和上一种是类似的。
4.看看多重嵌套的情况,为了简便,我们嵌套两层:
{
"id" : 1,
"data" : {
"name" : "wu",
“age” : 26
}
}
- std::string json = "{\"id\" : 1, \"data\" : { \"name\" : \"wu\", \"age\" : 26 } }";
- Json::Reader reader;
- Json::Value root;
- std::string name;
- int id = 0;
- int age = 0;
- if (reader.parse(json, root)) // reader将Json字符串解析到root,root将包含Json里所有子元素
- {
- id = root["id"].asInt();
- name = root["data"]["name"].asString();
- age = root["data"]["age"].asInt();
- }
其实这种情况和第一种的类似,只是通过root["key"]取到的还是键值对,继续通过key取值即可。
基本上再复杂的数据格式也是上面几种情况的组合而已。
json对象的生成:
1.生成上面第一种情况的json格式:
- Json::Value root;
- root["id"] = 123;
- root["name"] = "wu";
- std::string json = root.toStyledString();
我们会将生成的json对象序列化到string对象中去,后面也是如此。
2.生成上面第二种情况的json:
- Json::Value root;
- for (int i = 0; i < 2; ++i)
- {
- root[i]["id"] = i + 1;
- if (0 == i)
- {
- root[i]["name"] = "wu";
- }
- else
- {
- root[i]["name"] = "tan";
- }
- }
- std::string json = root.toStyledString();
还可以这样生成:
- Json::Value root;
- Json::Value item;
- for (int i = 0; i < 2; ++i)
- {
- item["id"] = i + 1;
- if (0 == i)
- {
- item["name"] = "wu";
- }
- else
- {
- item["name"] = "tan";
- }
- root.append(item);
- }
- std::string json = root.toStyledString();
3.生成上面第三种情况的json:
- Json::Value root;
- for (int i = 0; i < 2; ++i)
- {
- root["id"].append(i);
- if (0 == i)
- {
- root["name"].append("wu");
- }
- else
- {
- root["name"].append("tan");
- }
- }
- std::string json = root.toStyledString();
4.生成上面第四种情况的json:
- Json::Value root;
- root["id"] = 1;
- root["data"]["name"] = "wu";
- root["data"]["age"] = 26;
- std::string json = root.toStyledString();
其实解析和生成json是互逆的,只要明白这几种情况,其他的无非是这几种情况的各种组合,原理是一样的。
版权声明:本文为博主原创文章,未经博主允许不得转载。
jsoncpp的api简要说明的更多相关文章
- ElasticSearch API 简要介绍
调用其API会返回很多信息,例如集群的信息,节点的信息等 检查集群的状态----Restful API说明 1:检查集群状态信息 2:管理集群 3:执行 增删改查 命令 4:执行高级命令 Restfu ...
- HTML5权威指南--Web Storage,本地数据库,本地缓存API,Web Sockets API,Geolocation API(简要学习笔记二)
1.Web Storage HTML5除了Canvas元素之外,还有一个非常重要的功能那就是客户端本地保存数据的Web Storage功能. 以前都是用cookies保存用户名等简单信息. 但是c ...
- HTML5权威指南--标签新变化,文件API,拖放API(简要学习笔记一)
1.标签元素更加语义化 2.内容类型仍然为“text/html” 扩展符仍然为html或者htm. <1>DOCTYPE 声明<!DOCTYPE html>就可 ...
- jsoncpp第二篇------API
更多API参考jsoncpp头文件 1 jsoncpp的api简要说明 1,解析(json字符串转为对象) std::string strDataJson; Json::Reader JReader ...
- 010 使用netmap API接管网卡,接收数据包,回应ARP请求
一.本文目的: 上一节中,我们已经在CentOS 6.7 上安装好了netmap,也能接收和发送包了,这节我们来调用netmap中的API,接管网卡,对网卡上收到的数据包做分析,并回应ARP请求. 二 ...
- sql server远程备份和恢复
sql server远程备份和恢复 SQLSERVER服务实例名称:192.168.0.2需要备份的数据库名称: a备份机器名称(Client端):192.168.0.3备份机用户:zf 密码:123 ...
- Math类中的BigDecimal
如果我们编译运行下面这个程序会看到什么? public class Test { public static void main(String args[]) { ...
- Java浮点数float,bigdecimal和double精确计算的精度误差问题总结
(转)Java浮点数float,bigdecimal和double精确计算的精度误差问题总结 1.float整数计算误差 案例:会员积分字段采用float类型,导致计算会员积分时,7位整数的数据计算结 ...
- 关于java中Double类型的运算精度问题
标题 在Java中实现浮点数的精确计算 AYellow(原作) 修改 关键字 Java 浮点数 精确计算 问题的提出:如果我们编译运行下面这个程序会看到什么?publi ...
随机推荐
- 枚举 || CodeForces 742B Arpa’s obvious problem and Mehrdad’s terrible solution
给出N*M矩阵,对于该矩阵有两种操作: 1.交换两列,对于整个矩阵只能操作一次 2.每行交换两个数. 交换后是否可以使每行都递增. *解法:N与M均为20,直接枚举所有可能的交换结果,进行判断 每次枚 ...
- sftp ftp文件同步方案
sftp ftp文件同步方案 1. 需求 1.1实现网关服务器的ftp服务器的/batchFileRequest目录下文件向徽商所使用的sftp服务器的/batchFileRequest目录同步文件 ...
- svn搭建脚本
1.yum install subversion 2.输入rpm -ql subversion查看安装位置 我们知道svn在bin目录下生成了几个二进制文件. 输入 svn --help可以查看svn ...
- Ducci Sequence解题报告
A Ducci sequence is a sequence of n-tuples of integers. Given an n-tuple of integers (a1, a2, ... , ...
- Nowcoder 106 C.Professional Manager(统计并查集的个数)
题意: 给出四种操作: 1. 合并u,v两棵树 2. 从u所在的集合中删除u 3. 询问u所在集合有多少颗树 4. 询问 u,v是否在同一个集合 分析: 对于删除操作, 只要新开一个点代替原来的点即可 ...
- MongoDB中WiredTiger的数据可用性设置
此文已由作者温正湖授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. MongoDB中WiredTiger的参数配置主要通过 wiredtiger_open (http://so ...
- javascript:与获取鼠标位置有关的属性
javascript并没有mouse对象,获取鼠标坐标要靠强大的event对象。 我们通过监听document的mousemove,就可以实时获得鼠标位置。 但是!!event中和鼠标相关的属性太多了 ...
- xtu summer individual 4 C - Dancing Lessons
Dancing Lessons Time Limit: 5000ms Memory Limit: 262144KB This problem will be judged on CodeForces. ...
- C. The Smallest String Concatenation-C++sort排序~~
C. The Smallest String Concatenation time limit per test 3 seconds memory limit per test 256 megabyt ...
- HDU 4597
题目大意: 两人轮流从两堆牌从抽取最顶端或者最底部的牌,得到的分数加到自己身上,问先拿牌的最多能得多少分 记忆化搜索,2堆牌的底和顶,有四种方法,根据四种方法来找到最优解 #include <c ...