什么是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. CFILE追加写入文件

    CFile file; file.Open(strName, CFile::modeWrite|CFile::modeNoTruncate|CFile::modeCreate); ) { file.S ...

  2. 自己配置的WAMP环境,扩展oracle函数库(oci)

    同事昨天接到一个任务,要用php处理oracle数据库的内容,但是php打开oracle扩展不是像mysql那样直接用就行,需要下一点东西才能打开 第一步 需要到oracle官方下载一个install ...

  3. Python进阶之自定义排序函数sorted()

    sorted() .note-content {font-family: "Helvetica Neue",Arial,"Hiragino Sans GB",& ...

  4. Java生成缩略图之Thumbnailator

    Thumbnailator 是一个为Java界面更流畅的缩略图生成库.从API提供现有的图像文件和图像对象的缩略图中简化了缩略过程,两三行代码就能够从现有图片生成缩略图,且允许微调缩略图生成,同时保持 ...

  5. python特性、属性以及私有化

    python中特性attribute 特性是对象内部的变量 对象的状态由它的特性来描述,对象的方法可以改变它的特性 可以直接从对象外部访问特性 特性示例: class Person: name = ' ...

  6. Scala数组操作实战详解

    增删改查,要注意的是,Array数组是定长数组,ArrayBuffer数组才是变长数组. 其他集合也存在可变不可变.例如,List,Set,Map 多维数组定义方法与Java类似.

  7. Activity之间定时跳转

    起源:很多应用在打开时,首先会加载欢迎页面,经过几秒后再跳转到主页面. 下面,我通过两种不同的方式来实现页面的定时跳转. 第一种方式: 通过Timer类的schedule方法. 实现从MainActi ...

  8. [原创]obj-c编程17:键值观察(KVO)

    原文链接:[原创]obj-c编程17:键值观察(KVO) 系列专栏链接:objective-c 编程系列 说完了前面一篇KVC,不能不说说它的应用KVO(Key-Value Observing)喽.K ...

  9. Java学习疑惑(8)----可视化编程, 对Java中事件驱动模型的理解

    我们编写程序就是为了方便用户使用, 我觉得UI设计的核心就是简洁, 操作过于繁琐的程序让很大一部分用户敬而远之. 即使功能强大, 但是人们更愿意使用易于操作的软件. 近年流行起来的操作手势和逐渐趋于成 ...

  10. [LeetCode][Python]14: Longest Common Prefix

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com'https://oj.leetcode.com/problems/longest ...