我在嵌入式平台中使用 cJson for C 来构建这样的 JSON:
{"ProtocolVersion":1,"ID":"123","Zone":"xyz","MessageType":42,"Message":"Json payload MSG #6"}
为此,我使用 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);
要创建 json,我使用了以下函数:
cJSON_PrintPreallocated( jsonObject, *jsonMessage, *jsonMessageLen, 0 );
我更喜欢将我的应用程序预先分配的缓冲区传递给 cJson,并且我基本上通过将每个 Key 和 Object 的长度相加来计算缓冲区长度。
例如:strlen("Zone") + strlen(xyzStr) + ... + "" 的数量 + {} 的数量 + 的数量,+ 的数量:
通过这种方式,我获得了 JSON 的确切长度。
不幸的是,函数“cJSON_PrintPreallocated”由于缓冲区长度不正确(似乎很短)而失败。
如果我在“jsonMessage”中添加额外的 30 个字节,一切正常。
我哪里错了?
计算 cJson 所需的缓冲区长度的最佳方法是什么?
谢谢!