cJSON库使用的问题,cJSON库解析长整形有限制,最长只有double类型

cJSON的介绍

符合MIT许可证的超轻量,可移植,单文件,简单易于ANSI-C兼容的JSON解析器。
github的下载 [https://github.com/DaveGamble/cJSON]

主要介绍遇到的一个问题

想通过cJSON库解析较长的整数的时,库无法处理。

  1. 这个是cJSON库,解析整数的代码,使用的double类型接收。
/* Parse the input text to generate a number, and populate the result into item. */
static const char *parse_number(cJSON *item,const char *num)
{
	double n=0,sign=1,scale=0;int subscale=0,signsubscale=1;

	if (*num=='-') sign=-1,num++;	/* Has sign? */
	if (*num=='0') num++;			/* is zero */
	if (*num>='1' && *num<='9')	do	n=(n*10.0)+(*num++ -'0');	while (*num>='0' && *num<='9');	/* Number? */
	if (*num=='.' && num[1]>='0' && num[1]<='9') {num++;		do	n=(n*10.0)+(*num++ -'0'),scale--; while (*num>='0' && *num<='9');}	/* Fractional part? */
	if (*num=='e' || *num=='E')		/* Exponent? */
	{	num++;if (*num=='+') num++;	else if (*num=='-') signsubscale=-1,num++;		/* With sign? */
		while (*num>='0' && *num<='9') subscale=(subscale*10)+(*num++ - '0');	/* Number? */
	}

	n=sign*n*pow(10.0,(scale+subscale*signsubscale));	/* number = +/- number.fraction * 10^+/- exponent */
	
	item->valuedouble=n;
	item->valueint=(int)n;
	item->type=cJSON_Number;
	return num;
}

这段代码就不分析了,都能看懂就是字符的数字解析成数字。
2. cJSON的结构体

/* The cJSON structure: */
typedef struct cJSON {
	struct cJSON *next,*prev;	/* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
	struct cJSON *child;		/* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */

	int type;					/* The type of the item, as above. */

	char *valuestring;			/* The item's string, if type==cJSON_String */
	int valueint;				/* The item's number, if type==cJSON_Number */
	double valuedouble;			/* The item's number, if type==cJSON_Number */

	char *string;				/* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
} cJSON;

很显然是double valuedouble不能够存储较长的整形的,double类型的精度不够,需要修改为需要用的long long 类型。 我是这么理解的,如果你们有什么好的方法,请评论分享下。

本来较长的数字可以不适用长整形存储,可以使用字符串格式存储,就不会出现精度的问题了,可是接受到的JSON格式目前只能是整数。所以暂时的把库给改了改。希望你们有好方法介绍。

注:double类型存储只能保证15位一下的纯整数存储正确的形式。

睡觉了,描述的不是很清楚。

你可能感兴趣的:(遇到的问题记录)