I'm using cJson for C, into an embedded platform, to build a JSON like this:
{"ProtocolVersion":1,"ID":"123","Zone":"xyz","MessageType":42,"Message":"Json payload MSG #6"}
To do this I use this function provided by cJson:
jsonObject = cJSON_CreateObject();
/* Add Protocol Version */
cJSON_AddNumberToObject( jsonObject, "ProtocolVersion", 1);
/* Add Machine Id */
cJSON_AddStringToObject( jsonObject, "ID", idStr );
/* Add Market */
cJSON_AddStringToObject( jsonObject, "Zone", xyzStr);
/* Add Message Type */
cJSON_AddNumberToObject( jsonObject, "MessageType", typeNum);
/* Add Message */
cJSON_AddStringToObject( jsonObject, "Message", msgStr);
To create the json I used the function:
cJSON_PrintPreallocated( jsonObject, *jsonMessage, *jsonMessageLen, 0 );
I prefer to pass to cJson a buffer preallocated by my application and I compute the buffer length basically by sum the length of each Key and Object.
For example: strlen("Zone") + strlen(xyzStr) + ... + Number of "" + Number of {} + Number of , + Number of :
In this way I obtain the exact length of my JSON.
Unfortunately, the function "cJSON_PrintPreallocated" fails due to a incorrect buffer length (it seems to short).
If I add an extra 30 bytes to my "jsonMessage" everything works.
Where I'm wrong?
Which is the best way to compute the buffer length required by cJson?
Thanks!