0

I developing a C embedded software that build a JSON string with several parameters ( string and integer ). For my purpose I used cJSON ) in future I need to parse complex JSON).

I build my json with this code:

  jsonObject = cJSON_CreateObject();

  cJSON_AddNumberToObject( jsonObject, "Version", 1 );

  cJSON_AddStringToObject( jsonObject, "ID", "xyz" );

  cJSON_AddStringToObject( jsonObject, "Local", "1234" );

  cJSON_AddNumberToObject( jsonObject, "Type", 1 );

  cJSON_AddStringToObject( jsonObject, "Message", "Hello" );

Next I print the JSON into a dynamic buffer using:

cJSON_PrintPreallocated( jsonObject, *jsonMessage, *jsonMessageLen, 0 )

When I visualise the jsonMessage on a terminal, the property "Type" hasn't a value.

This is the built json:

{"Version":1,"ID":"xyz","Local":"123","Type":,"Message":"Hello"}

I try to use a different print method, for example I used:

CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt)

And the JSON is built correctly. The problem is that I need to allocate the memory by myself and not using cJSON_PrintBuffered. This because I cannot use malloc and free function.

Any suggestions?

Thanks

Federico
  • 1,117
  • 6
  • 20
  • 37

2 Answers2

0

I updated the cJSON module and now it works fine.

Federico
  • 1,117
  • 6
  • 20
  • 37
0

This is kind of interesting, I believe I know what is going on. Sorry for any inconveniences I caused by writing that bug ...

In version 1.4.0 I introduced a bug to cJSON that the function that prints numbers didn't fail when it couldn't allocate enough memory.

print_number will try to allocate 64 bytes of memory before printing a number, because it doesn't know how many bytes sprintf will need and snprintf is not available in ANSI C. Your preallocated buffer probably wasn't long enough for the 64 bytes, so it didn't print the number one, but then continued printing the rest of the JSON normally because it didn't fail (the bug).

I added a note to the header file today: Your preallocated has to be 63 bytes longer than what you expect the printed json to be if you want to avoid any kind of out of situation where cJSON aborts because it thinks it doesn't have enough memory in the preallocated buffer.

FSMaxB
  • 2,280
  • 3
  • 22
  • 41