1 Star 1 Fork 0

itfriday / sax-json-c

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

sax-json-c

1. 简介

sax-json是一个sax2风格的JSON解析器。它读取JSON文档并根据在文档中遇到的特定符号生成事件,它不会在内存中为文档创建树结构,相反,它按顺序处理文档的内容并在读取文档时生成事件。 比如针对下面的JSON实例:

{
    "meeting_info":
    {
        "meeting_id": 123,
        "meeting_title": "meeting"
    }
}

在解析时,sax-json会依次触发以下事件:

  1. onStartElement("meeting_info")
  2. onStartElement("meeting_id")
  3. onEndElement("meeting_id", "123", kJsonValueTypeNumber, 0)
  4. onStartElement("meeting_title")
  5. onEndElement("meeting_title", "meeting", kJsonValueTypeString, 0)
  6. onEndElement("meeting_info", "", kJsonValueTypeObject, 0)

和xml sax解析器一样,开发者需要实现处理这些事件的处理函数来完成解析后处理功能。

2. 使用说明

sax-json采用标准c语言编写,支持windows、linux、mac。要使用sax-json,只需要将源码下载并添加到项目中即可。

在使用sax-json时,有两种方式可供选择:

  1. 仅使用sax-json的解析功能,在项目中实现onStartElement及onEndElement事件处理函数
  2. 使用sax-json封装好的JsonLoader,将JSON字符串或JSON文件加载解析成c结构体

2.1 sax-json解析功能使用说明

JSON解析功能是在json/JsonParser代码中完成的,如果开发者只想使用JSON解析功能,可以只添加json/JsonParser及其依赖文件到项目中。事实上json/JsonParser来自我的另一个项目CBase

直接使用JSON解析功能,是需要开发者自己实现解析器抛出的onStartElement及onEndElement事件的,相比较使用封装好的json/JsonLoader会麻烦一点。

  1. 将以下文件添加到项目中:

    comm/ErrorCode.h
    comm/BaseFuncDef.h
    json/JsonParser.h
    json/JsonParser.c

  2. 定义并实现sax-json解析事件处理函数:

    onStartElement: json中子字段开始事件处理函数
    onEndElement: json中子字段结束事件处理函数
    onParseError: json解析出错事件处理函数

  3. 调用以下两个函数解析字符串或文件:

    parse_json_string: 解析JSON字符串
    parse_json_file: 解析JSON文件

2.2 JsonLoader使用说明

使用json/JsonLoader可以将JSON字符串或JSON文件解析成c结构对象。在解析过程中,JsonLoader需要c结构对象与JSON对象之间的对应关系,这个对应关系可以使用pp描述文件(类似Protocol Buffer)来定义,之后使用tools/CMessage-Creator/generator.py工具,将pp描述文件转成c语言文件。转换后的c文件也需要添加到项目中一起编译使用。

具体步骤如下:

  1. 将sax-json所有源代码添加到项目中
  2. 参考2.3节,编写pp描述文件,定义c结构与JSON对象之间的对应关系
  3. 使用tools/CMessage-Creator/generator.py工具,将pp描述文件转成c语言文件
  4. 将转换生成的c文件添加到项目中
  5. 项目中使用生成的函数解析字符串或文件:

    <结构体名>_from_json: 解析JSON字符串,填充c结构体
    <结构体名>_from_file: 解析JSON文件,填充c结构体
    <结构体名>_to_json: c结构体对象转成json字符串

可以参考example目录下的例子:

  • example/meeting.pp 定义c结构的pp文件
  • example/main.c 例子主程序
  • example/Makefile linux及mac上的makefile文件
  • example/Example.sln windows上visual studio 2022项目文件
  • example/pp/Meeting.h 使用tools/CMessage-Creator/generator.py工具,将meeting.pp转换后的c结构定义头文件
  • example/pp/Meeting.c 使用tools/CMessage-Creator/generator.py工具,将meeting.pp转换后的c结构定义源文件

2.3 pp描述文件编写指南

pp描述文件可以定义c结构体与JSON对象之间的对应关系。在pp文件中可以定义常量(c 宏定义)、枚举(c enum)、结构体(c struct)、联合体(c union)。

2.3.1 定义结构体:

使用struct关键字定义结构体,其语法格式和c语言定义结构体的语法格式类似,见下面的例子:

// 会议信息
struct MeetingInfo {
    string MeetingID[MAX_MEETING_ID_LEN];  `json:"meeting_id"`   // 会议ID
    uint8  MeetingType;                    `json:"meeting_type"` // 会议类型
    uint8  MeetingState;                   `json:"meeting_state"`// 会议状态
    int64  BeginTM;                        `json:"begin_tm"`     // 会议开始时间
    uint8  ChatterNumber;                  `json:"chatter_number"`// 语音会议中聊天人数量
    uint64 Chatters[MAX_CHATTER_NUMBER] => ChatterNumber; `json:"chatters"` // 语音会议中聊天者UID
};

它定义了一个名为MeetingInfo的结构体,包含6个字段:

  1. MeetingID: 使用string定义的一个字符串字段,注意定义字符串字段时需要指定最大长度。这里MeetingID字符串的最大长度是MAX_MEETING_ID_LEN
  2. MeetingType:使用uint8定义的一个8bit的无符号整型字段
  3. MeetingState:使用uint8定义的一个8bit的无符号整型字段
  4. BeginTM:使用int64定义的一个64bit的有符号整型字段
  5. ChatterNumber:使用uint8定义的一个8bit的有符号整型字段
  6. Chatters:使用uint64定义的一个64bit的无符号整型数组字段,注意定义数组字段时需要指定数组最大数量,并需要使用"=>"指定数组真实数量字段。这里数组字段Chatters最大能保存MAX_CHATTER_NUMBER个uint64的整数,而当前保存的数组个数由结构体中第5个字段ChatterNumber保存

此外:

  • 字段的json名称由分号;后面的json:"JSON名"来指定,比如本例中,字段MeetingID的JSON名称是meeting_id。若不指定json名,则字段本名将作为字段的JSON名。
  • pp文件中"//"开头的文本为注释
  • 可以在pp文件中定义常量,并在定义字段时使用这个常量。比如本例中,MAX_MEETING_ID_LEN和MAX_CHATTER_NUMBER都是定义的常量
  • 除了本例中使用的几个类型(string, uint8, int64, uint64)来定义字段外,pp能支持的类型汇总如下:
类型 类型说明
uint8 无符号整数,C语言中占1个字节,JSON中对应Number
int8 有符号整数,C语言中占1个字节,JSON中对应Number
uint16 无符号整数,C语言中占2个字节,JSON中对应Number
int16 有符号整数,C语言中占2个字节,JSON中对应Number
uint32 无符号整数,C语言中占4个字节,JSON中对应Number
int32 有符号整数,C语言中占4个字节,JSON中对应Number
uint64 无符号整数,C语言中占8个字节,JSON中会自动转换成string
int64 有符号整数,C语言中占8个字节,JSON中会自动转换成string
string 字符串类型,定义字符串字段时需要指定最大长度

使用tools/CMesage-Creator/generator.py工具,将pp定义的结构体MeetingInfo转换的c代码如下:

/**
 * 会议信息
 */
struct MeetingInfo
{
	char szMeetingID[MAX_MEETING_ID_LEN];     /* 会议ID */
	uint8_t chMeetingType;                    /* 会议类型 */
	uint8_t chMeetingState;                   /* 会议状态 */
	int64_t llBeginTM;                        /* 会议开始时间 */
	uint8_t chChatterNumber;                  /* 语音会议中聊天人数量 */
	uint64_t astChatters[MAX_CHATTER_NUMBER]; /* 语音会议中聊天者UID */
};

2.3.1 结构体嵌套:

定义结构体时,使用其他结构体定义子字段,可以实现结构体嵌套定义,如下例使用结构体MeetingInfo定义了一个结构体数组字段:

// 会议列表
struct MeetingList {
    uint32      MeetingNumber;   `json:"meeting_number"` // 列表中会议数量
    MeetingInfo	MeetingInfos[MAX_MEETING_NUMBER] => MeetingNumber `json:"meeting_infos"`    // 列表中会议信息
};

2.3.2 定义联合

联合体在c语言中可以节省内存,虽然JSON没有联合体,但是在c语言中可以使用联合体。

在pp中,使用union关键字定义联合,其语法格式和c语言定义联合的语法格式类似,见下面的例子:

// 会议信息
union MeetingData {
    MeetingList MeetingList; `json:"meeting_list" tag:"MEETING_DATA_TYPE_LIST"` // 会议列表
    MeetingInfo MeetingInfo; `json:"meeting_info" tag:"MEETING_DATA_TYPE_INFO"` // 会议信息
};

注意,定义联合时,联合的子字段,必须使用tag标签指定联合的选择的值,上例中:

  • MeetingList字段只有当联合MeetingData的选择值是MEETING_DATA_TYPE_LIST时有效
  • MeetingInfo字段只有当联合MeetingData的选择值是MEETING_DATA_TYPE_INFO时有效

联合体MeetingData转换成c代码如下:

/**
 * 会议信息
 */
struct MeetingData
{
	uint16_t nSelector;
	union
	{
		MEETINGLIST stMeetingList; /* 会议列表 */
		MEETINGINFO stMeetingInfo; /* 会议信息 */
	};
};

可见,转换后,MeetingData被自动加上了nSelector字段,它是联合的选择器,当nSelector=MEETING_DATA_TYPE_LIST时,字段stMeetingList有效;当nSelector=MEETING_DATA_TYPE_INFO时,字段stMeetingInfo有效

2.3.3 定义常量

使用关键字const定义常量:

// 宏定义
const MAX_MEETING_ID_LEN = 128;     // 最大会议ID长度
const MAX_MEETING_NUMBER = 128;     // 会议列表中最大会议数量
const MAX_CHATTER_NUMBER = 8;       // 语音会议中最大聊天人数量

2.3.4 定义枚举

使用关键字enum定义枚举:

// 会议类型
enum MeetingType {
    MEETING_TYPE_NORMAL = 0,    // 普通会员
    MEETING_TYPE_AUDIO = 1,     // 语音会议
    MEETING_TYPE_VIDEO = 2,     // 视频会议
};

2.3.5 pp文件中的module

在pp文件中,可以使用module关键字定义模块,将pp中定义的常量、枚举、结构体、联合都归类于这个模块中。参考meeting.pp中module的定义:

module meeting {
    // 宏定义
    const MAX_MEETING_ID_LEN = 128;     // 最大会议ID长度
    // 其他 ...
};

由于c语言不支持namespace概念,所以这里module的定义是可选的。

2.4 pp代码生成器使用说明

代码生成器位于tools/CMessage-Creator目录,它是python编写的工具,不需要编译可以跨平台使用。它需要python2.4以上的环境

代码生成器的主程序是generator.py,执行python generator.py --help可以查看帮助。

Description: message generator.
Version: 1.0.0.0
Usage: python generator.py [-?] [-h] [-s DIRECTORY] [-d DIRECTORY] [-m FILE_NAME]

optional arguments:
  -?, -h, --help        Show this help information
  -s DIRECTORY, --srcpath DIRECTORY
                        Set pp define file search directory
  -d DIRECTORY, --directory DIRECTORY
                        Set generate project directory for project
  -f FILE_NAME
                        Set generate file name

Example:
  python generator.py --help
  python generator.py -s . -d ../test

可选输入参数说明如下:

可选参数:
  -?, -h, --help    显示本程序的帮助信息
  -s DIRECTORY, --srcpath DIRECTORY
        指定pp描述文件所在路径,注意路径中可以包含多个pp描述文件
  -d DIRECTORY, --directory DIRECTORY
        设置代码生成路径,该路径用来存放转换后的c语言文件
  -f FILE_NAME
        设置代码生成的c语言文件名称,若不指定,则使用pp描述文件中的module名
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

sax2风格的json解析,支持将json解析成c结构体 展开 收起
C 等 4 种语言
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C
1
https://gitee.com/itfriday/sax-json-c.git
git@gitee.com:itfriday/sax-json-c.git
itfriday
sax-json-c
sax-json-c
master

搜索帮助

344bd9b3 5694891 D2dac590 5694891