一个用C++写的Json解析与处理库
什么是Json?这个库能做什么?
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write.
Json 是一种轻量的数据交换格式,和 XML 一样在 Web 开发中非常常用。在 Ajax 的应用中,前台基本上会用到 JSON 作为数据交换格式,因为在 JS 里面可以通过 JSON.parse() 函数对 JSON 格式的字符串进行解析得到 JS 对象,通过这个 JS 对象可以轻松地获取和修改里面的数据。而这个库 ggicci::Json
可以像 JS 一样通过解析获得一个类似的 C++ 对象。通过这个 C++ 对象,你可以像使用 JS 一样对数据进行获取和修改,语法上基本类似。只不过 C++ 是强类型语言,所以当你在试图用不一样的数据类型去获取里面的值的时候会抛异常。至于 C++ 是否需要 JSON 解析器,答案是肯定的,比如某个 CS 架构的程序,服务器端有某些页面采用 web 技术输出 JSON 数据,客户端是 C++ 客户端,它向这些页面发送 HTTP 请求并接收到 JSON 数据,这些数据就需要解析以配合客户端的使用。当然除非客户端只是输出这些字符串或者客户端采用与 C++ 与 JS 混合编程方式,让 JS 去处理这些数据。
更好的阅读体验请传送门传送到我的个人博客对应地址:http://ggicci.me/wordpress/cpp/一个用c写的json解析与处理库/
项目地址和文档
Github:https://github.com/ggicci/ggicci--json
GGICCI:http://ggicci.me/works/json
文档:http://ggicci.me/works/json/doc
看一个简单例子
#include <iostream>
#include "gci-json.h" using namespace std;
using namespace ggicci; int main(int argc, char const *argv[])
{
// Parse a string to get a Json object
Json json = Json::Parse("{ \
\"id\": 18293, \
\"name\": \"Ggicci\", \
\"birthday\": [1991, 11, 10], \
\"man\": true \
}"); cout << "json = " << json << endl;
cout << "-----------------------" << endl;
cout << "id: " << json["id"] << endl;
cout << "name: " << json["name"] << endl;
cout << "birthday-year: " << json["birthday"][0] << endl;
cout << "birthday-month: " << json["birthday"][1] << endl;
cout << "birthday-day: " << json["birthday"][2] << endl;
cout << "man: " << boolalpha << json["man"] << endl;
cout << "-----------------------" << endl; json["name"] = "Mingjie Tang";
// add property: method 1
json["school"] = "Northwest A&F University";
// add property: method 2
json.AddProperty("traits", Json::Parse("[]").Push("sympathetic").Push("independent"));
cout << "json = " << json << endl;
cout << "-----------------------" << endl; json["birthday"].Remove(0);
json.Remove("id").Remove("school");
cout << "json = " << json << endl; return 0;
} /*
output:
-----------------------
id: 18293
name: "Ggicci"
birthday-year: 1991
birthday-month: 11
birthday-day: 10
man: true
-----------------------
json = { "birthday": [ 1991, 11, 10 ], "id": 18293, "man": true, "name": "Mingjie Tang", "school": "Northwest A&F University", "traits": [ "sympathetic", "independent" ] }
-----------------------
json = { "birthday": [ 11, 10 ], "man": true, "name": "Mingjie Tang", "traits": [ "sympathetic", "independent" ] }
*/
如果你对 JSON 的处理比较熟悉(你可能会使用 JS 处理 JSON 数据),你会发现上面的代码很好理解。
与 JS 的使用比较(语法层面上)
对于原始的 JSON 字符串 str: { "id": 1000, "name": "ggicci", "birthday": [1991, 11, 10] }
JS: var str = '{ "id": 1000, "name": "ggicci", "birthday": [1991, 11, 10] }';
C++: const char* str = "{\"id\": 1000, \"name\": \"ggicci\", \"birthday\": [1991, 11, 10] }";
功能 | JS 的 JSON 解析器 | ggicci::Json(下面假设已声明使用命名空间 ggicci) |
解析并得到JSON对象 | var json = JSON.parse(str); |
Json json = Json::Parse(str); |
获取Number | var id = json["id"]; |
int id = json["id"]; |
获取String | var name = json["name"]; |
const char* name = json["name"]; string name = json["name"]; |
获取Array | var birthday = json["birthday"]; |
Json birthday = json["birthday"]; // 拷贝 Json &birthday = json["birthday"]; // 引用 Json *birthday = json["birthday"]; // 指针 |
ggicci::Json 中获取 null(需要通过 Json 对象,IsNull() 函数用来确定接收到的数据是否是 null) 获取Object(需要通过 Json 对象) 获取true,false(通过 bool 值就可以了) | ||
修改Number | json["id"] = 19214; |
json["id"] = 19214; |
修改String | json["name"] = "Mingjie Tang"; |
json["name"] = "Mingjie Tang"; |
修改Array | json["birthday"][2] = 11; |
json["birthday"][2] = 11; |
添加数据(Array) | json["birthday"].push(2013); json["birthday"].push("hello"); |
json["birthday"].Push(2013).Push("hello"); |
添加数据(Object) | json["man"] = true; |
json["man"] = true; json.AddProperty("man", true); |
删除数据(Array) | use pop, unshift ... | json["birthday"].Remove(0); // 不能级联 |
删除数据(Object) | delete json["name"]; |
json.Remove("name").Remove("id"); // 可以级联 |
获取Object的所有Keys | // 复杂 |
vector<string> keys = json.Keys(); |
异常处理
解析异常
int main(int argc, char const *argv[])
{
try
{
Json json = Json::Parse("[1, 2, 2, { \"id\": 183, \"name\": 'Ggicci' } ]");
}
catch (exception& e)
{
cout << e.what() << endl; // SyntaxError: Unexpected token ' at pos 31
}
return 0;
}
在 Chrome 下利用 JS 的 JSON::parse() 函数解析抛出的异常:
数据获取异常
int main(int argc, char const *argv[])
{
try
{
Json json = Json::Parse("[1, 2, 3, 4]");
int first = json[0]; // no problem
const char* second = json[1]; // cause exception
}
catch (exception& e)
{
cout << e.what() << endl; // OperationError: Illegal extract opeartion from Number to String
}
return 0;
}
非法操作异常
int main(int argc, char const *argv[])
{
try
{
Json json = Json::Parse("[1, 2, 3, 4]");
json.AddProperty("name", "Ggicci"); // cause exception
}
catch (exception& e)
{
cout << e.what() << endl; // OperationError: Illegal add property opeartion on Array
}
return 0;
}
类型检测
int main(int argc, char const *argv[])
{
Json json = Json::Parse("[1, \"hello\", { \"title\": null }, false ]");
json.IsArray(); // true
json[0].IsNumber(); // true
json[1].IsString(); // true
json[2].IsObject(); // true
json[2]["title"].IsNull(); //true
json[3].IsBool(); // true if (json.IsArray())
{
for (int i = 0; i < json.Size(); ++i)
{
switch (json[i].DataKind())
{
case Json::kNumber: cout << "number: "; break;
case Json::kString: cout << "string: "; break;
case Json::kArray: cout << "array: "; break;
case Json::kObject: cout << "object: "; break;
case Json::kBool: cout << "bool: "; break;
case Json::kNull: cout << "null: "; break;
default: break;
}
cout << json[i] << endl;
}
}
return 0;
} /*
output:
number: 1
string: "hello"
object: { "title": null }
bool: false
*/
写在最后
如果可以,请你使用
一个用C++写的Json解析与处理库的更多相关文章
- java中常见的json解析方法、库以及性能对比
常见的json解析有原生的JSONObject和JSONArray方法,谷歌的GSON库,阿里的fastjson,还有jackson,json-lib. Gson(项目地址:https://githu ...
- cJSON: 一个用c写的一个简单好用的JSON解析器
转自:http://blog.csdn.net/chenzhongjing/article/details/9188347 下载地址: http://sourceforge.net/projects/ ...
- 一起写一个JSON解析器
[本篇博文会介绍JSON解析的原理与实现,并一步一步写出来一个简单但实用的JSON解析器,项目地址:SimpleJSON.希望通过这篇博文,能让我们以后与JSON打交道时更加得心应手.由于个人水平有限 ...
- 手写Json解析器学习心得
一. 介绍 一周前,老同学阿立给我转了一篇知乎回答,答主说检验一门语言是否掌握的标准是实现一个Json解析器,网易游戏过去的Python入门培训作业之一就是五天时间实现一个Json解析器. 知乎回答- ...
- Json解析工具Jackson(简单应用)
原文http://blog.csdn.net/nomousewch/article/details/8955796 概述 Jackson库(http://jackson.codehaus.org),是 ...
- Android 中Json解析的几种框架(Gson、Jackson、FastJson、LoganSquare)使用与对比
介绍 移动互联网产品与服务器端通信的数据格式,如果没有特殊的需求的话,一般选择使用JSON格式,Android系统也原生的提供了JSON解析的API,但是它的速度很慢,而且没有提供简介方便的接口来提高 ...
- 高性能JSON解析器及生成器RapidJSON
RapidJSON是腾讯公司开源的一个C++的高性能的JSON解析器及生成器,同时支持SAX/DOM风格的API. 直击现场 RapidJSON是腾讯公司开源的一个C++的高性能的JSON解析器及生成 ...
- java 写一个JSON解析的工具类
上面是一个标准的json的响应内容截图,第一个红圈”per_page”是一个json对象,我们可以根据”per_page”来找到对应值是3,而第二个红圈“data”是一个JSON数组,而不是对象,不能 ...
- Tomjson - 一个"短小精悍"的 json 解析库
Tomjson,一个"短小精悍"的 json 解析库,tomjson使用Java语言编写,主要作用是把Java对象(JavaBean)序列化为json格式字符串,将json格式字符 ...
随机推荐
- hdu4507
数位dp,终于守得云开见月明了.建议初学者先试试两道比较简单的hdu2089,hdu3555. 鸣谢:http://blog.csdn.net/acm_cxlove/article/details/8 ...
- web.xml加载顺序详解
一. 1.启动tomcat启动web项目,首先读取web.xml文件中<context-param>和<listener> 2.容器创建一个ServletContext(ser ...
- The method replace(int, Fragment, String) in the type FragmentTransaction is not applicable for the arguments (int, SettingFragment, String)
The method replace(int, Fragment, String) in the type FragmentTransaction is not applicable for the ...
- 写一个jq插件
本文章摘自博客园的http://www.cnblogs.com/JustinYoung/archive/2010/03/30/jquery-chajian.html,写此文章只是方便自己记载技术 一个 ...
- QT连接mysql中文显示问题
亲测OK! #vim /etc/mysql/my.cnf [mysqld]下面加入: default-character-set=utf8 重启mysql /etc/init.d/mysql rest ...
- 20.org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actua ...
- Java安全学习
http://blog.csdn.net/wbw1985/article/details/5506515 http://blog.csdn.net/wbw1985/article/details/60 ...
- 製程能力介紹(SPC introduction) ─ 製程能力的三種表示法
製程能力的三種表示法 Ck: 準度指標 (accuracy) Ck=(M-X)/(T/2) Cp: 精度指標 (precision) Cp=T/(6σp) 規格為單邊時:Cp=(Tu-X)/3 ...
- Nginx和Nginx+的比较(上)
Nginx和Nginx+的比较(上) 作者:chszs,未经博主允许不得转载.经许可的转载需注明作者和博客主页:http://blog.csdn.net/chszs 一.Nginx+介绍 Nginx和 ...
- Oracle Dataguard HA (主备,灾备)方案部署调试
包括: centos6.5 oracle11gR2 DataGuard安装 dataGuard 主备switchover角色切换 数据同步测试 <一,>DG数据库数据同步测试1,正常启动主 ...