内存管理

可以修改内存管理函数,自己实现mallocreallocfree,详细参考:自定义malloc分配数组空间

内存释放

使用cJSON_free释放cJSON_PrintcJSON_PrintUnformattedcJSON_PrintBuffered申请的字符串空间。

使用cJSON_Delete释放生成的JSON对象。

控制浮点数小数位数

没有找到cJSON本身的接口,但可以自己创建函数实现。

1
2
3
4
5
6
7
void cJSON_AddDoubleToObject(cJSON *const object, const char* const name, const double number, const unsigned int precision)
{
if(precision > 15) return;
char num_string[26] = {0};
snprintf(num_string, sizeof(num_string), "%1.*lf", precision, number);
cJSON_AddRawToObject(object, name, num_string);
}

以上有点小瑕疵,即当浮点数本身小数位不到设置的长度时,也会补上0。下面的迂回修改可以解决这个问题。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int digits(int a)
{
int res = 0;
do
{
a /= 10;
res++;
}while(a!=0);

return res;
}

void cJSON_AddDoubleToObject(cJSON *const object, const char* const name, const double number, const unsigned int precision)
{
if(precision > 15) return;
char num_string[26] = {0};
int pcs = precision + digits((int)number);
snprintf(num_string, sizeof(num_string), "%1.*g", pcs, number);
cJSON_AddRawToObject(object, name, num_string);
}

控制浮点数数组小数位

和上边类似,修改原cJSON_CreateDoubleArray函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
CJSON_PUBLIC(cJSON*) cJSON_CreateDoubleArray_pcs(const double *numbers, int count, unsigned int precision)
{
size_t i = 0;
cJSON *n = NULL;
cJSON *p = NULL;
cJSON *a = NULL;

if(precision > 15) NULL;

if ((count < 0) || (numbers == NULL))
{
return NULL;
}

a = cJSON_CreateArray();

for(i = 0; a && (i < (size_t)count); i++)
{
char num_string[26] = {0};
//int pcs = precision + digits((int)numbers[i]);
//snprintf(num_string, sizeof(num_string), "%1.*g", pcs, numbers[i]);
snprintf(num_string, sizeof(num_string), "%1.*lf", precision, numbers[i]);
n = cJSON_CreateRaw(num_string);
if(!n)
{
cJSON_Delete(a);
return NULL;
}
if(!i)
{
a->child = n;
}
else
{
suffix_object(p, n);
}
p = n;
}

if (a && a->child) {
a->child->prev = n;
}

return a;
}

多维数组

参考一维数组的生成代码,编写多维数组,以下是2维浮点数数组。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
CJSON_PUBLIC(cJSON*) cJSON_CreateDouble2dArray_pcs(const double **numbers, int x, int y, unsigned int precision)
{
size_t i = 0;
cJSON *n = NULL;
cJSON *p = NULL;
cJSON *a = NULL;

if(precision > 15) NULL;

if ((x < 0) || (y < 0) || (numbers == NULL))
{
return NULL;
}

a = cJSON_CreateArray();

for(i = 0; a && (i < x); i++)
{

n = cJSON_CreateDoubleArray_pcs(numbers[i], y, precision);

if(!i)
{
a->child = n;
}
else
{
suffix_object(p, n);
}
p = n;
}

if(a && a->child)
{
a->child->prev = n;
}

return a;
}

注意多维数组指针的使用方式

二维数组如:

1
int a[2][3];

其指针的定义方式为:

1
int *pa[2] = {a[0], a[1]};   //数组指针

作为函数参数传递,函数的定义有两种

1
2
3
4
5
6
7
void func1(int **p, int x, int y)
{
}

void func2(int (*p)[3], int x) //指针数组
{
}

对这两种定义,调用方式为

1
2
func1(pa,2,3);
func2(a,2);