我编写了以下程序:
#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);
}
由于某种原因,最后一个
fprintf(stdout, "%s\n", selection->valuestring);
命令打印出 (null)
,而它应该是 1,因为我在 Json 对象中指定了“选择”为 1。为什么会发生这种情况?有人可以帮我吗?
我找到了一些关于如何执行此操作的指南,并且跳过了将文件中的 json 数据解析到缓冲区,然后解析到 json 对象的部分。我刚刚创建了一个新的 Json 对象,今天就到此为止了。 https://www.geeksforgeeks.org/cjson-json-file-write-read-modify-in-c/
这是我的代码的完整输出:
{
"selection": 1,
"sockethandle": 100
}
(null)
您要求的是
selection->valuestring
,但 selection
是一个整数。它没有字符串值,这就是为什么你会得到 (null)
。你想要:
fprintf(stdout, "%d\n", selection->valueint);
进行此更改后,您的代码将产生:
{
"selection": 1,
"sockethandle": 100
}
1