I have written the following program:
#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);
}
For some reason, the final fprintf(stdout, "%s\n", selection->valuestring);
command prints out (null)
while it should be 1, because I specified "selection" to be 1 inside the Json object. Why is this happening? Can anyone help me out?
I found some guide on how to do it and I skipped the part where I parse the json data from a file into a buffer and then into a json object. I just made a new Json object and called it a day. https://www.geeksforgeeks.org/cjson-json-file-write-read-modify-in-c/
This is the full output of my code:
{
"selection": 1,
"sockethandle": 100
}
(null)
You are asking for selection->valuestring
, but selection
is an integer. It has no string value, which is why you are getting (null)
. You want:
fprintf(stdout, "%d\n", selection->valueint);
With that change, your code produces:
{
"selection": 1,
"sockethandle": 100
}
1