核心特性
标准兼容性:严格遵循 ECMA-404 JSON 标准,确保解析的准确性。
内存安全:无堆分配,使用内部堆栈跟踪嵌套结构,避免内存泄漏。
可移植性:符合 ISO C90 和 MISRA C:2012 标准,支持多种平台。
嵌套深度控制:通过 JSON_MAX_DEPTH 宏(默认 32 级)限制嵌套深度,防止栈溢出。
JSON_Validate:验证 JSON 文档的合法性。
JSON_Search:查找 JSON 对象中的键值对,支持嵌套查询。
JSON_Iterate:遍历 JSON 对象的键值对。
#include <stdio.h>
#include "core_json.h"
int main()
{
// Variables used in this example.
JSONStatus_t result;
char buffer[] = "{\"foo\":\"abc\",\"bar\":{\"foo\":\"xyz\"}}";
size_t bufferLength = sizeof( buffer ) - 1;
char queryKey[] = "bar.foo";
size_t queryKeyLength = sizeof( queryKey ) - 1;
char * value;
size_t valueLength;
// Calling JSON_Validate() is not necessary if the document is guaranteed to be valid.
result = JSON_Validate( buffer, bufferLength );
if( result == JSONSuccess )
{
result = JSON_Search( buffer, bufferLength, queryKey, queryKeyLength,
&value, &valueLength );
}
if( result == JSONSuccess )
{
// The pointer "value" will point to a location in the "buffer".
char save = value[ valueLength ];
// After saving the character, set it to a null byte for printing.
value[ valueLength ] = '\0';
// "Found: bar.foo -> xyz" will be printed.
printf( "Found: %s -> %s\n", queryKey, value );
// Restore the original character.
value[ valueLength ] = save;
}
return 0;
}嵌套深度:通过 JSON_MAX_DEPTH 宏调整最大嵌套层级。
错误处理:API 返回状态码(如 JSONNotFound)指示操作结果。
coreJSON 适合需要高效 JSON 解析的嵌入式项目,尤其在资源受限的物联网设备中表现优异。
我要赚赏金
