简体   繁体   中英

Calculate the byte size of a cJSON object

Right now I'm struggling with calculating the size of a cJSON object. So far, I have done this:

cJSON *payload = cJSON_CreateObject();
...
size_t size_payload = sizeof(payload);

Obviously I initialize the payload object and I print into the terminal to verify the integrity of the data and it is ok. However, after printing the sizeof result, it is always 4 as the number of bytes, but for a long string (as mine) it should be around 500 bytes.

Am I missing something here handling cJSON object?

Hope you can help, or maybe give me an example of how to get the proper value of the entire size.

sizeof() is a compile-time constant. It has no concept of data at runtime.

sizeof(payload) is the byte size of your payload variable, which is declared as a cJSON* pointer. So its byte size is always the same - sizeof(void*) , which is 4 bytes in your case (because you are compiling your app for 32bit). Its size is not that of the cJSON object that it is pointing at.

And even then, if you tried to dereference the pointer and use sizeof() on the cJSON object itself, ie sizeof(*payload) , it would be the byte size of the cJSON struct itself at compile-time , not the byte size of any data that the cJSON object has allocated internally for itself at runtime .

AFAICS, cJSON does not provide a method for returning the byte size of the JSON data it is holding, so you will just have to format the JSON to a string variable, and then query that string for its size at runtime, eg:

char *str = cJSON_Print(payload); // or cJSON_PrintUnformatted() or cJSON_PrintBuffered() ...
if (str) {
    size_t len = strlen(str);
    cJSON_free(str);
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM