- CMake 多目标工程:shs_core 静态库 + smart_home 可执行 + shs_tests 测试 - CMakePresets.json:debug/release/asan/coverage 四个预设(debug 告警即错误) - 自研零依赖测试框架 tests/framework/test_framework.h + 运行器(套件过滤、CTest 集成) - 工具:tools/header_check.sh 头文件独立编译检查(接口冻结门) - 已实现公共层:errors / string_utils / num_utils,main 启动自检 - 实测:debug 预设 0 告警、ctest 3/3 通过(45 项断言)
55 lines
2.1 KiB
C
55 lines
2.1 KiB
C
/**
|
||
* @file json.h
|
||
* @brief 极简 JSON 生成与取值(零第三方依赖)
|
||
*
|
||
* 教材对应:项目五 字符数组与字符串拼接 · 项目七 指针游标 ·
|
||
* 项目八 结构体 · 项目九 字符转义(数据安全)。
|
||
* 用途:网页上位机(/api 系列接口)与 C 程序之间的数据交换。
|
||
*/
|
||
#ifndef SHS_JSON_H
|
||
#define SHS_JSON_H
|
||
|
||
#include "shs/common.h"
|
||
#include "shs/errors.h"
|
||
|
||
/** JSON 写出器:持有输出缓冲与写入位置 */
|
||
typedef struct {
|
||
char *buf; /**< 输出缓冲(调用方提供) */
|
||
size_t cap; /**< 缓冲容量 */
|
||
size_t len; /**< 已写入长度 */
|
||
int depth; /**< 嵌套深度 */
|
||
bool need_comma; /**< 下一个元素前是否需要逗号 */
|
||
bool overflow; /**< 是否发生过溢出(写入被截断) */
|
||
} json_writer_t;
|
||
|
||
/** 初始化写出器 */
|
||
void json_init(json_writer_t *w, char *buf, size_t cap);
|
||
/** 结束并返回缓冲指针;写入过程发生过溢出时返回的内容仍以 '\0' 结尾 */
|
||
const char *json_result(json_writer_t *w);
|
||
bool json_ok(const json_writer_t *w);
|
||
|
||
void json_begin_object(json_writer_t *w);
|
||
void json_end_object(json_writer_t *w);
|
||
void json_begin_array(json_writer_t *w);
|
||
void json_end_array(json_writer_t *w);
|
||
|
||
void json_key(json_writer_t *w, const char *key);
|
||
void json_string(json_writer_t *w, const char *value);
|
||
void json_int(json_writer_t *w, long value);
|
||
void json_uint(json_writer_t *w, unsigned long value);
|
||
void json_double(json_writer_t *w, double value, int decimals);
|
||
void json_bool(json_writer_t *w, bool value);
|
||
void json_null(json_writer_t *w);
|
||
|
||
/** 把字符串转义为 JSON 安全文本(\" \\ \n \t 控制字符转 \uXXXX) */
|
||
int json_escape(const char *in, char *out, size_t out_size);
|
||
|
||
/** 从 JSON 文本中取字符串字段(用于解析 POST 请求体) */
|
||
shs_err_t json_get_string(const char *json, const char *key, char *out, size_t out_size);
|
||
/** 取整数字段 */
|
||
shs_err_t json_get_int(const char *json, const char *key, long *out);
|
||
/** 取布尔字段 */
|
||
shs_err_t json_get_bool(const char *json, const char *key, bool *out);
|
||
|
||
#endif /* SHS_JSON_H */
|