这些小活动你都参加了吗?快来围观一下吧!>>
电子产品世界 » 论坛首页 » 嵌入式开发 » STM32 » CoreJSON库介绍

共2条 1/1 1 跳转至

CoreJSON库介绍

院士
2025-12-19 09:04:16     打赏

coreJSON 是 FreeRTOS 中的一个轻量级 JSON 解析库,专为资源受限的嵌入式系统设计,适用于物联网微控制器。以下是其核心特性和使用方法:

核心特性
  1. 标准兼容性‌:严格遵循 ECMA-404 JSON 标准,确保解析的准确性。

  2. 内存安全‌:无堆分配,使用内部堆栈跟踪嵌套结构,避免内存泄漏。

  3. 可移植性‌:符合 ISO C90 和 MISRA C:2012 标准,支持多种平台。

  4. 嵌套深度控制‌:通过 JSON_MAX_DEPTH 宏(默认 32 级)限制嵌套深度,防止栈溢出。

主要 API
  • 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 解析的嵌入式项目,尤其在资源受限的物联网设备中表现优异。





关键词: CoreJSON    

专家
2025-12-19 09:22:48     打赏
2楼

之前一直使用cjson。有机会我也试试这个json库


共2条 1/1 1 跳转至

回复

匿名不能发帖!请先 [ 登陆 注册 ]