微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

cJSON 使用详解

由于c语言中,没有直接的字典,字符串数组等数据结构,所以要借助结构体定义,处理json。如果有对应的数据结构就方便一些, 如python中用json.loads(json)就把json字符串转变为内建的数据结构处理起来比较方便。

cjson库文件下载

sourceforge地址

下载完之后读一下,README。

编译方式

在工程中添加cJSON.c 和cJSON.h 编译即可,不过要添加-lm链接库gcc选项,如:

gcccJSON.cmain.c-omain-lm

添加-lm是因为用到了,数学库有关的函数

一个重要概念:

在cjson中,json对象可以是json,可以是字符串,可以是数字。。。

cjson数据结构定义

#definecJSON_False0
#definecJSON_True1
#definecJSON_NULL2
#definecJSON_Number3
#definecJSON_String4
#definecJSON_Array5
#definecJSON_Object6

typedefstructcJSON{
structcJSON*next,*prev;/*next/prevallowyoutowalkarray/objectchains.Alternatively,useGetArraySize/GetArrayItem/GetobjectItem*/
structcJSON*child;/*Anarrayorobjectitemwillhaveachildpointerpointingtoachainoftheitemsinthearray/object.*/

inttype;/*Thetypeoftheitem,asabove.cjson结构的类型上面宏定义的7中之一*/

char*valuestring;/*Theitem'sstring,iftype==cJSON_String*/
intvalueint;/*Theitem'snumber,iftype==cJSON_Number*/
doublevaluedouble;/*Theitem'snumber,iftype==cJSON_Number*/

char*string;/*Theitem'snamestring,ifthisitemisthechildof,orisinthelistofsubitemsofanobject.*/
}cJSON;

一、解析json

用到的函数,在cJSON.h中都能找到:

/*SupplyablockofJSON,andthisreturnsacJSONobjectyoucaninterrogate.CallcJSON_Deletewhenfinished.*/
externcJSON*cJSON_Parse(constchar*value);//从给定的json字符串中得到cjson对象
/*RenderacJSONentitytotextfortransfer/storage.Freethechar*whenfinished.*/
externchar*cJSON_Print(cJSON*item);//从cjson对象中获取有格式的json对象
/*RenderacJSONentitytotextfortransfer/storagewithoutanyformatting.Freethechar*whenfinished.*/
externchar*cJSON_PrintUnformatted(cJSON*item);//从cjson对象中获取无格式的json对象

/*DeleteacJSONentityandallsubentities.*/
externvoidcJSON_Delete(cJSON*c);//删除cjson对象,释放链表占用的内存空间

/*Returnsthenumberofitemsinanarray(orobject).*/
externintcJSON_GetArraySize(cJSON*array);//获取cjson对象数组成员的个数
/*Retrieveitemnumber"item"fromarray"array".ReturnsNULLifunsuccessful.*/
externcJSON*cJSON_GetArrayItem(cJSON*array,intitem);//根据下标获取cjosn对象数组中的对象
/*Getitem"string"fromobject.Caseinsensitive.*/
externcJSON*cJSON_GetobjectItem(cJSON*object,constchar*string);//根据键获取对应的值(cjson对象)

/*ForanalysingFailedparses.Thisreturnsapointertotheparseerror.You'llprobablyneedtolookafewcharsbacktomakesenSEOfit.DefinedwhencJSON_Parse()returns0.0whencJSON_Parse()succeeds.*/
externconstchar*cJSON_GetErrorPtr(void);//获取错误字符串

要解析的json

{
"semantic":{
"slots":{
"name":"张三"
}
},"rc":0,"operation":"CALL","service":"telephone","text":"打电话给张三"
}


代码

#include<stdio.h>
#include<stdlib.h>
#include"cJSON.h"

voidprintJson(cJSON*root)//以递归的方式打印json的最内层键值对
{
for(inti=0;i<cJSON_GetArraySize(root);i++)//遍历最外层json键值对
{
cJSON*item=cJSON_GetArrayItem(root,i);
if(cJSON_Object==item->type)//如果对应键的值仍为cJSON_Object就递归调用printJson
printJson(item);
else//值不为json对象就直接打印出键和值
{
printf("%s->",item->string);
printf("%s\n",cJSON_Print(item));
}
}
}

intmain()
{
char*jsonStr="{\"semantic\":{\"slots\":{\"name\":\"张三\"}},\"rc\":0,\"operation\":\"CALL\",\"service\":\"telephone\",\"text\":\"打电话给张三\"}";
cJSON*root=NULL;
cJSON*item=NULL;//cjson对象

root=cJSON_Parse(jsonStr);
if(!root)
{
printf("Errorbefore:[%s]\n",cJSON_GetErrorPtr());
}
else
{
printf("%s\n","有格式的方式打印Json:");
printf("%s\n\n",cJSON_Print(root));
printf("%s\n","无格式方式打印json:");
printf("%s\n\n",cJSON_PrintUnformatted(root));

printf("%s\n","一步一步的获取name键值对:");
printf("%s\n","获取semantic下的cjson对象:");
item=cJSON_GetobjectItem(root,"semantic");//
printf("%s\n",cJSON_Print(item));
printf("%s\n","获取slots下的cjson对象");
item=cJSON_GetobjectItem(item,"slots");
printf("%s\n","获取name下的cjson对象");
item=cJSON_GetobjectItem(item,"name");
printf("%s\n",cJSON_Print(item));

printf("%s:",item->string);//看一下cjson对象的结构体中这两个成员的意思
printf("%s\n",item->valuestring);


printf("\n%s\n","打印json所有最内层键值对:");
printJson(root);
}
return0;
}

二、构造json

构造 json比较简单,添加json对象即可。参照例子一看大概就明白了。

主要就是用,cJSON_AddItemToObject函数添加json节点。

externcJSON*cJSON_CreateObject(void);
externvoidcJSON_AddItemToObject(cJSON*object,constchar*string,cJSON*item);

externcJSON*cJSON_CreateNull(void);
externcJSON*cJSON_CreateTrue(void);
externcJSON*cJSON_CreateFalse(void);
externcJSON*cJSON_CreateBool(intb);
externcJSON*cJSON_CreateNumber(doublenum);
externcJSON*cJSON_CreateString(constchar*string);
externcJSON*cJSON_CreateArray(void);
externcJSON*cJSON_CreateObject(void);

例子:

要构建的json:

{
"semantic":{
"slots":{
"name":"张三"
}
},"text":"打电话给张三"
}

代码

#include<stdio.h>
#include"cJSON.h"

intmain()
{
cJSON*root=cJSON_CreateObject();
cJSON*item=cJSON_CreateObject();
cJSON*next=cJSON_CreateObject();

cJSON_AddItemToObject(root,"rc",cJSON_CreateNumber(0));//根节点下添加
cJSON_AddItemToObject(root,"operation",cJSON_CreateString("CALL"));
cJSON_AddItemToObject(root,"service",cJSON_CreateString("telephone"));
cJSON_AddItemToObject(root,"text",cJSON_CreateString("打电话给张三"));
cJSON_AddItemToObject(root,"semantic",item);//root节点下添加semantic节点
cJSON_AddItemToObject(item,"slots",next);//semantic节点下添加item节点
cJSON_AddItemToObject(next,"name",cJSON_CreateString("张三"));//添加name节点

printf("%s\n",cJSON_Print(root));

return0;
}


代码工程链接

原文地址:https://www.jb51.cc/json/289530.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐