You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用cJSON库读取C语言JSON数据时取值出现null的问题排查

问题描述

我编写了如下C语言程序:

#include <stdio.h>
#include <cJSON.h> 

int main(){

    cJSON *jsoninput = cJSON_CreateObject(); 
    cJSON_AddNumberToObject(jsoninput, "selection", 1); 
    cJSON_AddNumberToObject(jsoninput, "sockethandle", 100); 

    char *json_str = cJSON_Print(jsoninput); 
    fprintf(stdout, "%s\n", json_str);
    
     
    cJSON *selection = cJSON_GetObjectItemCaseSensitive(jsoninput, "selection");


     fprintf(stdout, "%s\n", selection->valuestring);
}

程序打印JSON字符串正常,但最后通过selection->valuestring输出的是(null),而非预期的1。我跳过了从文件解析JSON到缓冲区再转为JSON对象的步骤,直接创建了JSON对象,请问该问题的原因是什么?

程序输出如下:

{
    "selection":    1,
    "sockethandle": 100

}
(null)
问题原因与解决方法

问题出在cJSON的类型存储机制上:

  • cJSON会根据节点的类型,把值存在不同的字段里:
    • 字符串类型的节点,值存在valuestring字段
    • 数字类型的节点,值存在valueint(整数)或valuedouble(浮点数)字段

你用cJSON_AddNumberToObject添加的是数字类型节点,所以selection->valuestring自然是null。要获取数字值,得用对应的字段:

修改后的代码片段:

// 先判断节点类型,避免空指针或类型错误
if (cJSON_IsNumber(selection)) {
    fprintf(stdout, "%d\n", selection->valueint); // 针对整数
    // 如果是浮点数,用下面的
    // fprintf(stdout, "%lf\n", selection->valuedouble);
}

这样就能正常输出预期的数字1了。

内容的提问来源于stack exchange,提问作者bangingmyheadontable

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 04:19:58