1、相关概念总结

(1)解析json的方法

Json::Value json;     //表示一个json格式的对象

Json::Reader reader;  //json解析

reader.parse(json_buf/*json格式的字符串*/,json,false);  //解析出json放到json中

jsoncpp库中的Reader类用来将字串或者流载入解析器。后期可以用Reader里面的解析方法把Json字串解码为C++认识的数据。可以用 Json::Reader来声明一个Reader实例。Reader中最常用的就是一个parse方法,该方法用来将载入的json字串解析为C++格式的数据。

(2) 数组访问

Json::Value //格式如下

[["key1":value1],["key2":value2]]

Json::Value::const_iterator iter;  //迭代器

for(iter = input.begin(); iter != input.end(); iter++)

Json::Value::Members member=(*iter).getMemberNames();

*(member.begin());          // 输出 key1,key2

(*iter)[*(member.begin())];     //输出 value1,value2

Value类是库中的核心类,用于存储各样格式的数据,可以包括int,double,short,char *,string,bool,object,array等几乎所有格式的数据。该库的编码和解码的核心功能都是用Value类实现的。就用以上的 Reader的parse方法来说,需要传入一个Value类别的引用值,就是用来存储Json数据的根值,并且可以用这个根值来存取其他的所有值。

(3) 对象访问

直接用 value["key"]即可

(4) 输出json格式串

调用 Json::FastWriter的writer

writer是该库的一个虚类,没有真正的实现encode的功能。需要重载里头的方法来实现真正的encode功能。FastWriter是该库中真正实现encode功能的类,用来实现将Value编码称为Json串。Json::StyledWriter 是格式化后的json。

不支持utf-8格式的输出,需要自己调用writer之后,用iconv转化成utf-8字符串

2、示例代码

1)示例代码1

View Code

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <string>#include <vector>#include <iostream>#include "json/json.h"using namespace std;

typedef struct piece {string letter;string wild;    }piece;

string encode_msg(string token,int game_id,vector<piece> piece_array){//Json::Value root;    Json::Value var;//apply “token” and “game_id” value to json struct    var["token"] = token;var["game_id"] = game_id;

    Json::Value pieces;//store all pieces    for (int i=0;i < piece_array.size();i++)    {        Json::Value piece_ex;//here it store just one piece//next 4 lines to apply piece value to json struct        piece_ex["letter"] = piece_array[i].letter;        piece_ex["wild"] = piece_array[i].wild;//ok,yes we just have apply One piece ,then push back to the array        pieces.append(piece_ex);    }var["piece_array"] = pieces;//yes,store pieces in var [Value]//root.append(var);

    Json::FastWriter writer;return writer.write(var);//generate json string:),here all is done}int main(){    piece one, two;    one.letter = "1";    one.wild = "ont";    two.letter = "2";    two.wild = "two";    vector<piece> myp;    myp.push_back(one);    myp.push_back(two);string ret = encode_msg("mytoken", 123, myp);    cout << ret << endl;return 1;}

View Code

{"game_id":123,"piece_array":[{"letter":"1","wild":"ont"},{"letter":"2","wild":"two"}],"token":"mytoken"}

结果显示

可以看到,直接用wirter输出的json为非格式化的数据,而通过root.toStyledString()后,代码就是格式化的。

2)示例3,来源于官网

View Code

// Configuration options{// Default encoding for text    "encoding" : "UTF-8",

// Plug-ins loaded at start-up    "plug-ins" : ["python","c++","ruby"        ],

// Tab indent size    "indent" : { "length" : 3, "use_space": true }}

View Code

Json::Value root;   // will contains the root value after parsing.Json::Reader reader;bool parsingSuccessful = reader.parse( config_doc, root );if ( !parsingSuccessful ){// report to the user the failure and their locations in the document.    std::cout  << "Failed to parse configuration\n"               << reader.getFormattedErrorMessages();return;}

// Get the value of the member of root named 'encoding', return 'UTF-8' if there is no// such member.std::string encoding = root.get("encoding", "UTF-8" ).asString();// Get the value of the member of root named 'encoding', return a 'null' value if// there is no such member.const Json::Value plugins = root["plug-ins"];for ( int index = 0; index < plugins.size(); ++index )  // Iterates over the sequence elements.   loadPlugIn( plugins[index].asString() );

setIndentLength( root["indent"].get("length", 3).asInt() );setIndentUseSpace( root["indent"].get("use_space", true).asBool() );

// ...// At application shutdown to make the new configuration document:// Since Json::Value has implicit constructor for all value types, it is not// necessary to explicitly construct the Json::Value object:root["encoding"] = getCurrentEncoding();root["indent"]["length"] = getCurrentIndentLength();root["indent"]["use_space"] = getCurrentIndentUseSpace();

Json::StyledWriter writer;// Make a new JSON document for the configuration. Preserve original comments.std::string outputConfig = writer.write( root );

// You can also use streams.  This will put the contents of any JSON// stream at a particular sub-value, if you'd like.std::cin >> root["subtree"];

// And you can write to a stream, using the StyledWriter automatically.std::cout << root;

参考

【1】 讲解说明

http://hi.baidu.com/%B4%AB%CB%B5%D6%D0%B5%C4%C8%CC%D5%DF%C3%A8/blog/item/a6eb970c98a644d67acbe15a.html

【2】 示例,该作者博文不错,涵盖了各个方面

http://hi.baidu.com/s_jqzhang/blog/item/a3c5df1f9408246ff624e4f5.html/cmtid/02e72e4fcb488039aec3ab28

【3】 boost库支持json比较好

http://freedomhui.com/?p=6

【3】 对json的类型作了简单的小结,为json-c进行了介绍

http://developer.51cto.com/art/201001/176060.htm

【4】 官网

http://jsoncpp.sourceforge.net/index.html

相关的类介绍及使用

http://jsoncpp.sourceforge.net/annotated.html

【5】 其他例子

http://joysofprogramming.com/json_parser_json-c/

http://forum.openframeworks.cc/index.php?topic=2833.0

7、JsonCpp简单使用(3)相关推荐

  1. 【超详细】C++Json:VS2015的jsoncpp库配置及简单使用

    Json Json是一种数据格式,本来是用于JavaScript的,但是因为他易读,格式明朗等原因,也被用于其他语言中. JsonCpp是一个C++的Json库,利用他我们可以进行数据传输,状态同步. ...

  2. c++json库(jsoncpp)简单使用(包含下载使用方法,中文错误解决方案)

    c++json库(jsoncpp)简单使用方法(含下载) 下载地址:jsoncpp的github仓库地址:open-source-parsers/jsoncpp: A C++ library for ...

  3. C++简单使用Jsoncpp来读取写入json文件

    一.源码编译 C++操作json字符串最好的库应该就是jsoncpp了,开源并且跨平台.它可以从这里下载. 下载后将其解压到任意目录,它默认提供VS2003和VS2010的工程文件,使用VS2010可 ...

  4. JsonCpp的简单使用方法

    JsonCpp 是一个C++用来处理JSON 数据的开发包.下面讲一下怎么使用JsonCpp来序列化和反序列化Json对象,以实际代码为例子.反序列化Json对象比如一个Json对象的字符串序列如下, ...

  5. C++调用JsonCpp库,json简单操作以及常用函数

    本文章记录作者对json操作的一点心得. 目录 准备 项目配置 代码 json格式说明 运用 初始化 调用时碰到的错误 准备 本文选择第三方库JsonCpp来解析json 下载地址:https://s ...

  6. QtCreator动态编译jsoncpp完美支持x86和arm平台

    如果是做嵌入式开发. 在Qt下支持JSon最好的办法,可能不是采用qjson这个库.QJson这个库的实例只提供了x86环境下的编译方法. Installing QJson ------------- ...

  7. C++用库 jsoncpp 解析 JSON

    使用C++处理JSON数据交换格式(转自http://hi.baidu.com/%D3%C3%B1%F8%C8%E7%C9%F1garbin/blog/item/85c602edd7f9a7fbcf1 ...

  8. Jsoncpp Compiler、Programming

    catalog 1. C++ jsoncpp简介 2. Jsoncpp的下载与编译 3. Linux Jsoncpp的SDK编译 & 简单实例 4. Windows Jsoncpp的SDK编译 ...

  9. VS2010中使用JSONCPP方法

    下载jsoncpp后,按ReadMe文档的说法是要先安装的,但是安装比较麻烦.然而事实上,我们并不需要安装,就可以直接使用. 方法一:直接拷贝源文件.这个方法比较简单,但不推荐,因为不便于项目管理. ...

最新文章

  1. 关于session共享
  2. 【干货】从零开始做运营(超详细脑图)
  3. Linux学习笔记(三)|Vim编辑器
  4. i219 2012驱动_2012年I / O之后
  5. 高颜值的故宫介绍html源码
  6. html画图代码_python之matplotlib画图教程(1)
  7. ActiveMQ-1 安装以及WebUI的配置
  8. ubuntu18.04系统下使用锐捷校园网两种方法:锐捷客户端登陆和Mentohust登陆方法
  9. 易宝支付 -- 微信小程序对接
  10. dsoframer.ocx java_dsoframer.ocx(java web 操作word) 总结一下
  11. apache commons-beanutils中BeanUtils和PropertyUtils区别
  12. 浏览器UserAgent发展历史
  13. ShFileOperation函数详解
  14. WCDMA中的CQI
  15. Linux操作系统基础之用户管理
  16. spring 自带的定时器task
  17. 10年后,程序员的薪资还会这么高么?
  18. python大数据之异常值处理
  19. python跑酷游戏源码_HTML5游戏实战(1):50行代码实现正面跑酷游戏
  20. mac上如何将python2.7修改为python3

热门文章

  1. predis操作大全
  2. U盘安装Ubuntu14.04 server版 提示无法挂载cd-rom数据的解决办法
  3. 之前画得太丑了,再来张好看的.我试着改小点.但是就看不清了
  4. RapidMiner数据挖掘入门
  5. 转载一篇阅读文章(还算不错吧)
  6. Go实现Raft第二篇:选举
  7. Linux的网卡由eth0变成了eth1,如何修复
  8. linux eclipse安装、新建并运行java程序
  9. Kubernetes--玩转Pod滚动更新123
  10. 面试官让我用channel实现sync包里的同步锁,是不是故意为难我?