cJSON代码阅读(9)——构造json数据的流程

cJSON_Print是构造json数据的主要函数,它内部调用print_value对你的数据进行格式化
print_value的主要流程:
1、首先判断节点的类型
2、如果是null、布尔类型,那么直接转换为字符串之后返回

3、否则,调用print_number对数值进行格式化,调用print_string对字符串进行格式化,,调用print_array对数组进行格式化,调用print_object对对象进行格式化

/* Render a value to text. */
// 将一个json节点转换为字符串
static char *print_value(cJSON *item,int depth,int fmt,printbuffer *p)
{
    char *out=0;

    if (!item)
        return 0;

    // 是否保存到打印缓存中
    if (p)
    {
        switch ((item->type)&255)
        {
        case cJSON_NULL:	{out=ensure(p,5);	if (out) strcpy(out,"null");	break;}
        case cJSON_False:	{out=ensure(p,6);	if (out) strcpy(out,"false");	break;}
        case cJSON_True:	{out=ensure(p,5);	if (out) strcpy(out,"true");	break;}
        case cJSON_Number:	out=print_number(item,p);break;
        case cJSON_String:	out=print_string(item,p);break;
        case cJSON_Array:	out=print_array(item,depth,fmt,p);break;
        case cJSON_Object:	out=print_object(item,depth,fmt,p);break;
        }
    }
    // 没有打印缓存,那么直接创建一个字符串缓存,然后把格式化后的字符串放入其中,然后返回
    else
    {
        switch ((item->type)&255)
        {
        // 如果是null,那么直接保存null字符串
        case cJSON_NULL:
            out=cJSON_strdup("null");	break;
            // 如果是布尔false,那么保存false字符串
        case cJSON_False:
            out=cJSON_strdup("false");break;
            // 如果是布尔true,那么保存true字符串
        case cJSON_True:
            out=cJSON_strdup("true"); break;
            // 如果是数值,那么格式化数值,然后保存
        case cJSON_Number:
            out=print_number(item,0);break;
            // 如果是字符串,那么格式化字符串
        case cJSON_String:
            out=print_string(item,0);break;
            // 如果是数组,那么格式化数组
        case cJSON_Array:
            out=print_array(item,depth,fmt,0);break;
            // 如果是对象(最开始一定是先调用这里),那么格式化对象
        case cJSON_Object:
            out=print_object(item,depth,fmt,0);break;
        }
    }
    // 返回格式化后的字符串
    return out;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值