作者:ilife

JsonCpp简单使用

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

#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; }
{"game_id":123,"piece_array":[{"letter":"1","wild":"ont"},{"letter":"2","wild":"two"}],"token":"mytoken"}

结果显示

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

2)示例3,来源于官网

// 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 } }
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

 

JsonCpp简单使用的更多相关文章

  1. JsonCpp 简单使用

    [转]自: http://www.cnblogs.com/ytjjyy/archive/2012/04/17/2453348.html JsonCpp 是一个C++用来处理JSON 数据的开发包.下面 ...

  2. JsonCpp的简单使用方法

    JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.易于人阅读和编写.同时也易于机器解析和生成.它基于JavaScript Programming Langu ...

  3. jsoncpp 源码编译与简单使用

    ******************************************************标准C++实现jsoncpp 源码使用编译(VC2012 MFC)(Qt5.2 Widget ...

  4. 【003:jsoncpp的简单使用】

    #include <json/json.h> #include <iostream> #include <string> using namespace std; ...

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

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

  6. jsoncpp初使用

    一 前言 由于最近一个c++项目需要使用json这种数据格式来传输数据, so上网去寻找合适的类库,毕竟对于这种不是很新的技术, 自己造轮子有点得不偿失. 从百度上翻了翻, 基本上就boost跟jso ...

  7. Jsoncpp Compiler、Programming

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

  8. SCons - 简单而强大的项目编译脚本

    N年前学的makefile,当时还勉强能写一些简单的工程编译,现在已经基本忘了.makefile确实编写复杂,而且平时也不是经常使用,容易忘记.偶识了scons,一切都变的简单了.最近研究了下scon ...

  9. QT 使用jsoncpp

    QT 使用jsoncpp 编译jsoncpp 编译前先安装好python,scons,解压jsoncpp到目录e:\jsconcpp,查看目录下的readme,有关于编译的说明的,根据说明做相应操作就 ...

随机推荐

  1. ThreadPoolExecutor机制探索-我们到底能走多远系列(41)

    我们到底能走多远系列(41) 扯淡: 这一年过的不匆忙,也颇多感受,成长的路上难免弯路,这个世界上没人关心你有没有变强,只有自己时刻提醒自己,不要忘记最初出发的原因. 其实这个世界上比我们聪明的人无数 ...

  2. MYSQL基本操作语句

    0.修改密码:mysqladmin -u root -p password 123456 导出数据库:mysqldump -u root -p yunpay>yunpay.sql 导入数据库:m ...

  3. kernel/Makefile

    ## Makefile for the linux kernel.## Note! Dependencies are done automagically by 'make dep', which a ...

  4. 关于CSS的那些事?

    关于CSS的那些事? 它有精准定位与排版,使得网页布局.信息排版一目了然:它有多姿多彩的样式属性,使得网页中各元素千变万化:它有神奇的渲染天赋,使得网页有了如诗如画.别具一格的魅力.你知道它了吗?没错 ...

  5. JavaWeb用Jdbc操作MySql数据库(二)

    一.仍然使用前面的环境和示例数据库. 二.建立发出注册请求的页面index3.jsp. <%@ page language="java" import="java. ...

  6. C# 中Join( )的理解

    在MSDN中对Join( )的解释比较模糊:在继续执行标准的 COM 和 SendMessage 消息泵处理期间,阻塞调用线程(线程A),直到某个线程终(线程B)止为止. 首先来看一下有关的概念: 我 ...

  7. MSP430精准配置高速串口波特率的方法

    引言     在实际项目大批量生产调试设备时,笔者发现同样版本的程序在不同设备上运行时效果不一致,一部分设备串口通信正常,另外一部分串口通信不正常.通过示波器对多个设备的串口波特率及系统时钟频率测试, ...

  8. python数据分析之pandas库的DataFrame应用二

    本节介绍Series和DataFrame中的数据的基本手段 重新索引 pandas对象的一个重要方法就是reindex,作用是创建一个适应新索引的新对象 ''' Created on 2016-8-1 ...

  9. [转]Could not load file or assembly 'System.Core, Version=2.0.5.0 和autofac冲突的问题

    Could not load file or assembly 'System.Core, Version=2.0.5.0 和autofac冲突的问题 来源:http://www.cnblogs.co ...

  10. JAVA监听器原理

    http://blog.csdn.net/longyulu/article/details/25054697 JAVA监听器原理 标签: 监听器 2014-05-05 15:40 9070人阅读 评论 ...