JSON是一种比XML更轻量级的数据交换格式,关于JSON的基础知识,参考 http://json.org/
JSON(JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.
cJSON也存在几个弱点:
1,不支持[1,2,3,]和{"one":1,}最后多余的那个逗号。这是C语言就开始支持的,JSON RFC文档中没有对此说明,只能说这是扩展功能吧。
2 ,不支持/*注释*/,和//单行注释。这也是扩展功能。C/C++/JAVA/JavaScript都支持注释,所以我也希望在json文件中写点注释。
3 ,使用了个全局变量指示出错位置。这个在多线程时就有问题啦。
4, 没有封装文件操作,用户需要自己读写文件。
虽然功能不是非常强大(上面124都是非常容易添加少数几行代码都可以支持的),但cJSON的小身板和速度是最值得赞赏的。其代码被非常好地维护着,结构也简单易懂,可以作为一个非常好的C语言项目进行学习(支持上面12两个功能可以作为学习后的作业)。其解析核心是通过递归函数完成的,不过放心它的每个函数都非常非常节省资源。
使用如下
void main()
{
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("Error before: [%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",str);
str=cJSON_GetObjectItem(item,"temp")->valuestring;
printf("temp: [%s]\n",str);
free(item);
}
free(root);
}
在cJSON.h中有如下定义
/* cJSON Types: */
#define cJSON_False 0
#define cJSON_True 1
#define cJSON_NULL 2
#define cJSON_Number 3
#define cJSON_String 4
#define cJSON_Array 5
#define cJSON_Object 6
下面这很详细 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)
{
case 0:
strcpy(out,pItem->valuestring);
break;
case 1:
sprintf(out,"%d",pItem->valueint);
break;
case 2://long long
sprintf(out,"%lld",pItem->valuellong);
break;
case 3://double
sprintf(out,"%lf",pItem->valuedouble);
break;
case 4: //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;
}
}
else if(pRoot->next)
pRoot=pRoot->next;
else break;
}while(!pItem&&pRoot);
pRoot=pRoot->child;
}