cJSON_AddNumberToObject 添加整型数据失败

原因是底层的sprintf  不支持 g参数,比如下面的

double d = item->valuedouble;
sprintf((char*)number_buffer, "%1.17g", d);
 
但是咱们底层的代码不支持 g,所以这个 函数是失效的,从而导致 cJSON_AddNumberToObject   失败
 
通俗说法,添加整型数据,就是用 sprintf 把整型添加进去
 
解决办法,修改下面的函数:
static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer)
{
    unsigned char *output_pointer = NULL;
    double d = item->valuedouble;
    int temp  = item->valueint;
    int length = 0;
    size_t i = 0;
    unsigned char number_buffer[26]; /* temporary buffer to print the number into */
    unsigned char decimal_point = get_decimal_point();
    // double test;

    if (output_buffer == NULL)
    {
        return false;
    }

    /* This checks for NaN and Infinity */
    if ((d * 0) != 0)
    {
        length = sprintf((char*)number_buffer, "null");
    }
    else
    {
        //lierda start qhq
        // /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */
        // sprintf

        // /* Check whether the original double can be recovered */
        // if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || ((double)test != d))
        // {
        //     /* If not, print with 17 decimal places of precision */
        //     length = sprintf((char*)number_buffer, "%1.17g", d);
        // }
        length = sprintf((char*)number_buffer, "%d", temp);
        //lierda end qhq
    }

    /* sprintf failed or buffer overrun occured */
    if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1)))
    {
        return false;
    }

    /* reserve appropriate space in the output */
    output_pointer = ensure(output_buffer, (size_t)length + sizeof(""));
    if (output_pointer == NULL)
    {
        return false;
    }

    /* copy the printed number to the output and replace locale
     * dependent decimal point with '.' */
    for (i = 0; i < ((size_t)length); i++)
    {
        if (number_buffer[i] == decimal_point)
        {
            output_pointer[i] = '.';
            continue;
        }

        output_pointer[i] = number_buffer[i];
    }
    output_pointer[i] = '\0';

    output_buffer->offset += (size_t)length;

    return true;
}

 

posted @ 2023-08-25 15:20  429512065  阅读(288)  评论(0编辑  收藏  举报