加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用cJSON

发布时间:2020-12-16 19:22:07 所属栏目:百科 来源:网络整理
导读:JSON是一种比XML更轻量级的数据交换格式,关于JSON的基础知识,参考http://json.org/ JSON (JavaScriptObjectNotation)isalightweightdata-interchangeformat.Itiseasyforhumanstoreadandwrite.Itiseasyformachinestoparseandgenerate.Itisbasedonasubsetoft

JSON是一种比XML更轻量级的数据交换格式,关于JSON的基础知识,参考http://json.org/

JSON(JavaScriptObjectNotation)isalightweightdata-interchangeformat.Itiseasyforhumanstoreadandwrite.Itiseasyformachinestoparseandgenerate.ItisbasedonasubsetoftheJavaScriptProgrammingLanguage,StandardECMA-2623rdEdition-December1999.JSONisatextformatthatiscompletelylanguageindependentbutusesconventionsthatarefamiliartoprogrammersoftheC-familyoflanguages,includingC,C++,C#,Java,JavaScript,Perl,Python,andmanyothers.ThesepropertiesmakeJSONanidealdata-interchangelanguage.

cJSON也存在几个弱点:

1,不支持[1,2,3,]和{"one":1,}最后多余的那个逗号。这是C语言就开始支持的,JSONRFC文档中没有对此说明,只能说这是扩展功能吧。

2,不支持/*注释*/,和//单行注释。这也是扩展功能。C/C++/JAVA/JavaScript都支持注释,所以我也希望在json文件中写点注释。

3,使用了个全局变量指示出错位置。这个在多线程时就有问题啦。

4,没有封装文件操作,用户需要自己读写文件。

虽然功能不是非常强大(上面124都是非常容易添加少数几行代码都可以支持的),但cJSON的小身板和速度是最值得赞赏的。其代码被非常好地维护着,结构也简单易懂,可以作为一个非常好的C语言项目进行学习(支持上面12两个功能可以作为学习后的作业)。其解析核心是通过递归函数完成的,不过放心它的每个函数都非常非常节省资源。

使用如下

voidmain()
{
char*jsonStr="{"weatherinfo":{"city":"宝鸡","cityid":"101110901","temp":"23","WD":"东风","WS":"2级","SD":"83%","WSE":"2","time":"18:00","isRadar":"0","Radar":""}}";
cJSON*root;
cJSON*item;
char*str;

root=cJSON_Parse(jsonStr);
if(!root)
{
printf("Errorbefore:[%s]n",cJSON_GetErrorPtr());
}
else
{
item=cJSON_GetObjectItem(root,"weatherinfo");
if(item)
{
str=cJSON_GetObjectItem(item,"city")->valuestring;
printf("city:[%s]n",str);
str=cJSON_GetObjectItem(item,"cityid")->valuestring;
printf("cityid:[%s]n","temp")->valuestring;
printf("temp:[%s]n",str);

free(item);
}
free(root);
}

在cJSON.h中有如下定义

/*cJSONTypes:*/
#definecJSON_False0
#definecJSON_True1
#definecJSON_NULL2
#definecJSON_Number3
#definecJSON_String4
#definecJSON_Array5
#definecJSON_Object6

下面这很详细copy过来看看:

原文:http://www.gejo.in/archives/690

cJSON*pRoot=cJSON_Parse(jsonString);
while(pRoot)
{
do
{
pItem=cJSON_GetObjectItem(pRoot,"Code");
if(pItem){
switch(pItem->type)
{
case0:
strcpy(out,pItem->valuestring);
break;
case1:
sprintf(out,"%d",pItem->valueint);
break;
case2://longlong
sprintf(out,"%lld",pItem->valuellong);
break;
case3://double
sprintf(out,"%lf",pItem->valuedouble);
break;
case4://array
nCount=cJSON_GetArraySize(pItem);//获取pArray数组的大小,仅对字符串元素?
for(i=0;i<nCount;i++)
{
pArrayItem=cJSON_GetArrayItem(pItem,i);
strcat(out,cJSON_Print(pArrayItem));
//sprintf(out,"%s",out,pArrayItem);
}
break;
}
}
elseif(pRoot->next)
pRoot=pRoot->next;
elsebreak;

}while(!pItem&&pRoot); pRoot=pRoot->child; }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读