要确定 cjson 对象保存的是指针还是字符串内容,写了如下测试代码
-
/*
-
* 测试 cJSON_AddStringToObject 保存的是指针还是内容
-
*/
-
#include <stdio.h>
-
#include <string.h>
-
#include "cJSON.h"
-
-
int main() {
-
cJSON *json = cJSON_CreateObject();
-
cJSON * string = NULL;
-
char str[128] = {0};
-
-
strcpy(str, "Hello World");
-
cJSON_AddStringToObject(json, "string", str);
-
memset(str, 0x00, sizeof(str));
-
string = cJSON_GetObjectItem(json, "string");
-
-
printf("str is [%s], string is [%s]\n", str, cJSON_GetStringValue(string));
-
cJSON_Delete(json);
-
return 0;
-
}
输出内容为
-
str is [], string is [Hello World]
可见
cjson 对象保存的是字符串内容
其实只需要看 cJSON 源代码就可以了
-
CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string)
-
{
-
cJSON *string_item = cJSON_CreateString(string);
-
if (add_item_to_object(object, name, string_item, &global_hooks, false))
-
{
-
return string_item;
-
}
-
-
cJSON_Delete(string_item);
-
return NULL;
-
}
-
-
CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string)
-
{
-
cJSON *item = cJSON_New_Item(&global_hooks);
-
if(item)
-
{
-
item->type = cJSON_String;
-
item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
-
if(!item->valuestring)
-
{
-
cJSON_Delete(item);
-
return NULL;
-
}
-
}
-
-
return item;
-
}
-
-
static unsigned char* cJSON_strdup(const unsigned char* string, const internal_hooks * const hooks)
-
{
-
size_t length = 0;
-
unsigned char *copy = NULL;
-
-
if (string == NULL)
-
{
-
return NULL;
-
}
-
-
length = strlen((const char*)string) + sizeof("");
-
copy = (unsigned char*)hooks->allocate(length);
-
if (copy == NULL)
-
{
-
return NULL;
-
}
-
memcpy(copy, string, length);
-
-
return copy;
-
}
阅读(1548) | 评论(0) | 转发(0) |