Federico
Federico

Reputation: 1157

cJson how to compute length of print buffer

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!

Upvotes: 1

Views: 1802

Answers (1)

FSMaxB
FSMaxB

Reputation: 2490

When printing numbers, cJSON conservatively reserves 64 bytes in the output buffer, because it can't know for sure how long a sprintf will print a number. In case of the number 1 this can mean that cJSON requests 63 bytes more than it actually needs.

This will probably change in a future version of cJSON, but for now there is now way around that.

To be safe you should always make your buffer 63 bytes longer than what you expect it to be.

UPDATE:

This has been updated. Since version 1.4.6 only requires 5 additional bytes.

Upvotes: 1

Related Questions