什么是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. EassyMock实践 自定义参数匹配器

    虽然easymock中提供了大量的方法来进行参数匹配,但是对于一些特殊场合比如参数是复杂对象而又不能简单的通过equals()方法来比较,这些现有的参数匹配器就无能为力了.easymock为此提供了I ...

  2. 终于解决“Git Windows客户端保存用户名与密码”的问题

    这就是正确答案,我们已经验证过了,下面详细描述一下解决方法: 1. 在Windows中添加一个HOME环境变量,值为%USERPROFILE%,如下图: 2. 在“开始>运行”中打开%Home% ...

  3. 判断浏览器及设备的打开方式,自动跳转app中

    如果安装了APP则自动条状app,如果没安装则自动跳转下载页面 <head> 放在head中加载 <script> function redirect() { var appU ...

  4. attempting to bokeyaunrun eclipse useing the jre instead of jdk,to run eclipse using

    关于eclipse运行出现,attempting to bokeyaunrun eclipse useing the jre instead of jdk,to run eclipse using错误 ...

  5. Android 常用代码片小结

    1. dp px 相互转换---------------public class DensityUtil { /** * 根据手机的分辨率从 dip 的单位 转成为 px(像素) */ public ...

  6. JQuerry 权威指南的都市笔记

    jquery 如今发展成集javascript.css.DOM .Ajax于一体的强大框架体系.他的主旨是以更少的代码,实现更多的功能(write less,do more) jquery  的进本功 ...

  7. MSI文件静默安装

    以.net4为例,以下命令为静默安装: dotNetFx40_Full_x86_x64.exe /q /norestart /ChainingPackage FullX64Bootstrapper / ...

  8. SQL Server Service Borker 1

    1.消息类型定义: 消息类型,是信息交换的模板.create message type message_type_name validattion = well_formed_xml; 2.约定定义: ...

  9. JS中String添加trim()方法

    这么牛的JS竟然还要自己封装trim方法. 下面利用prototype和正则表达式的添加方式添加trim(): <script language="javascript"&g ...

  10. Wafer管芯数量及成本估算

    芯片流片费用一般不按颗数计价,现在流片主要分为全晶圆和MPW两种方式.   MPW是现在很流行的一种tapout方法,主要是按晶圆面积来均分价格.   如果是整个wafer的话,成本主要是wafer费 ...