cJSON代码阅读(6)——解析JSON数值

来源:互联网 发布:淘宝订单险坑卖家 编辑:程序博客网 时间:2024/06/08 06:06
parse_number是进行json数值解析的函数。
1、首先判断数值是否有负号
2、跳过数值开头的0
3、计算数值的整数部分——从字符串转换为数字
4、计算数值的小数部分——从字符串转换为数字

5、返回下一个json数据的位置

/* 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? */    // 跳过开头的0    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;}


0 0
原创粉丝点击