什么是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] }";

ggicci::Json 和 JS 中 JSON 的使用比较
功能 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解析与处理库的更多相关文章

  1. java中常见的json解析方法、库以及性能对比

    常见的json解析有原生的JSONObject和JSONArray方法,谷歌的GSON库,阿里的fastjson,还有jackson,json-lib. Gson(项目地址:https://githu ...

  2. cJSON: 一个用c写的一个简单好用的JSON解析器

    转自:http://blog.csdn.net/chenzhongjing/article/details/9188347 下载地址: http://sourceforge.net/projects/ ...

  3. 一起写一个JSON解析器

    [本篇博文会介绍JSON解析的原理与实现,并一步一步写出来一个简单但实用的JSON解析器,项目地址:SimpleJSON.希望通过这篇博文,能让我们以后与JSON打交道时更加得心应手.由于个人水平有限 ...

  4. 手写Json解析器学习心得

    一. 介绍 一周前,老同学阿立给我转了一篇知乎回答,答主说检验一门语言是否掌握的标准是实现一个Json解析器,网易游戏过去的Python入门培训作业之一就是五天时间实现一个Json解析器. 知乎回答- ...

  5. Json解析工具Jackson(简单应用)

    原文http://blog.csdn.net/nomousewch/article/details/8955796 概述 Jackson库(http://jackson.codehaus.org),是 ...

  6. Android 中Json解析的几种框架(Gson、Jackson、FastJson、LoganSquare)使用与对比

    介绍 移动互联网产品与服务器端通信的数据格式,如果没有特殊的需求的话,一般选择使用JSON格式,Android系统也原生的提供了JSON解析的API,但是它的速度很慢,而且没有提供简介方便的接口来提高 ...

  7. 高性能JSON解析器及生成器RapidJSON

    RapidJSON是腾讯公司开源的一个C++的高性能的JSON解析器及生成器,同时支持SAX/DOM风格的API. 直击现场 RapidJSON是腾讯公司开源的一个C++的高性能的JSON解析器及生成 ...

  8. java 写一个JSON解析的工具类

    上面是一个标准的json的响应内容截图,第一个红圈”per_page”是一个json对象,我们可以根据”per_page”来找到对应值是3,而第二个红圈“data”是一个JSON数组,而不是对象,不能 ...

  9. Tomjson - 一个"短小精悍"的 json 解析库

    Tomjson,一个"短小精悍"的 json 解析库,tomjson使用Java语言编写,主要作用是把Java对象(JavaBean)序列化为json格式字符串,将json格式字符 ...

随机推荐

  1. Linux学习之nfs实例

    在对exports文件进行了正确的配置后,就可以启动NFS服务器了. 1.启动NFS服务器 为了使NFS服务器能正常工作,需要启动portmap和nfs两个服务,并且portmap一定要先于nfs启动 ...

  2. MyIsam与InnoDB主要区别

    MyIsam与InnoDB主要有以下4点大的区别,缓存机制,事物支持,锁定实现,数据物理存储方式(包括索引和数据). 1.缓存机制 myisam 仅仅缓存索引,不会缓存实际数据信息,他会将这一工作交给 ...

  3. C#学习日志 day8 -------------- async await 异步方法入门(引用博客)以及序列化和反序列化的XML及json实现

    首先是异步方法的介绍,这里引用自http://www.cnblogs.com/LoveJenny/archive/2011/11/01/2230933.html async and await 简单的 ...

  4. 简单的实现树莓派的WEB控制

    最终效果如图: 用到的知识:Python Bottle HTML Javascript JQuery Bootstrap AJAX 当然还有 linux 我去,这么多--我还是一点一点说起吧-- 先贴 ...

  5. Orchard 源码探索(Localization)之国际化与本地化

    本地化与国际化 基本上相关代码都在在Orchard.Framework.Localization中. T("english")是如何调用到WebViewPage.cs中的Local ...

  6. OAuth认证的过程

    在认证和授权的过程中涉及的三方包括:     服务提供方,用户使用服务提供方来存储受保护的资源,如照片,视频,联系人列表.     用户,存放在服务提供方的受保护的资源的拥有者.     客户端,要访 ...

  7. Android自定义View研究--View中的原点坐标和XML中布局自定义View时View触摸原点问题

    这里只做个汇总~.~独一无二 文章出处:http://blog.csdn.net/djy1992/article/details/9715047 Android自定义View研究--View中的原点坐 ...

  8. 强制杀oracle进程

    强制杀oracle进程: for p in `ps -ef| grep ora| awk '{print $2}'`;do kill -9 $p;done 修改 oracle xe 默认中文字符集成为 ...

  9. iptsbles及磁盘扩容

    如果你的IPTABLES基础知识还不了解,建议先去看看. 们来配置一个filter表的防火墙 1.查看本机关于IPTABLES的设置情况 [root@tp ~]# iptables -L -n Cha ...

  10. js中的刷新方法

    刷新并清除缓存: location.reload(true); 返回上一页并刷新: history.go(-1); location.reload(true); 子页面刷新父页面: self.open ...