使用cJSON

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; }

相关文章

AJAX是一种基于JavaScript和XML的技术,能够使网页实现异步交...
在网页开发中,我们常常需要通过Ajax从后端获取数据并在页面...
在前端开发中,经常需要循环JSON对象数组进行数据操作。使用...
AJAX(Asynchronous JavaScript and XML)是一种用于创建 We...
AJAX技术被广泛应用于现代Web开发,它可以在无需重新加载页面...
Ajax是一种通过JavaScript和HTTP请求交互的技术,可以实现无...