0

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)

1 Answer 1

2

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
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.