使用cjson解析json数据格式

一、Json数据格式

  • json是一种轻量级的数据传输格式,表示方法为:“名称”:“值”;
  • json通常的格式有两种,对象和数组
  • 对象由花括号括起来的逗号分割的成员构成,对象的成员可以是字符串、数值、数组、对象;

对象中包含字符串、数值、对象

{"name": "张三", "age": 18, "address": {"country" : "china", "province": "广东"}}
  • 数组是由方括号括起来的一组值构成,其内容也可以是字符串、数值、对象、数组。

数组元素是单纯的字符串:

["张三","李四","王五"]

数组元素是对象

[
  {
    "name":"张三",
    "age":20,
    "sex":"男"
  },
  {
    "name":"李四",
    "age":18,
    "sex":"女"
  }
]

二维数组

[
    ["countru": "中国""province": "四川"],
    ["countru": "中国""province": "广东"]
]

二、使用cjson解析和创建json数据

2.1. cjson结构体

cjson源码中使用cJSON结构体存储解析后的json数据,json数据的值可以是字符串、数组、对象、整型、浮点型:

#define cJSON_Number 3 //json的值为整型或者浮点型
#define cJSON_String 4 //json的值为字符串
#define cJSON_Array 5 //json的值为数组
#define cJSON_Object 6 //json的值为对象
typedef struct cJSON {
	struct cJSON *next,*prev;	/* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
	struct cJSON *child;		/* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */

	int type;					/* The type of the item, as above. */

	char *valuestring;			/* The item's string, if type==cJSON_String */
	int valueint;				/* The item's number, if type==cJSON_Number */
	double valuedouble;			/* The item's number, if type==cJSON_Number */

	char *string;				/* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
} cJSON;

2.2、cjson源码常用函数

/*
函数功能:将json格式的字符串转换成cJSON结构体
说明:这个函数会调用malloc动态分配内存,使用后必须调用cJSON_Delete函数释放内存。
*/
cJSON *cJSON_Parse(const char *value);
/*
函数功能:根据传入的名称,查找cJSON对象中对应的值
函数参数:object使用cJSON_Parse解析得到的cJSON结构体 string表示json对象的名称字符串
返回值:返回存储json名称、值、类型等数内容的结构体
*/
cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);
/*
函数功能:获取json数组的元素个数
*/
int	  cJSON_GetArraySize(cJSON *array);
/*
函数功能:初始化cJSON链表,分配内存空间
*/
cJSON *cJSON_CreateObject(void);
/*
函数功能:向json的object中添加对象元素
函数参数:object表示需要添加cJSON指针,string表示需要添加对象的名称,item表示需要添加对象的值
*/
void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item);
/* 向json数据中添加内容*/
#define cJSON_AddNullToObject(object,name)		cJSON_AddItemToObject(object, name, cJSON_CreateNull())
#define cJSON_AddTrueToObject(object,name)		cJSON_AddItemToObject(object, name, cJSON_CreateTrue())
#define cJSON_AddFalseToObject(object,name)		cJSON_AddItemToObject(object, name, cJSON_CreateFalse())
#define cJSON_AddBoolToObject(object,name,b)	cJSON_AddItemToObject(object, name, cJSON_CreateBool(b))
#define cJSON_AddNumberToObject(object,name,n)	cJSON_AddItemToObject(object, name, cJSON_CreateNumber(n))
#define cJSON_AddStringToObject(object,name,s)	cJSON_AddItemToObject(object, name, cJSON_CreateString(s))

2.3、示例

解析示例一:

char *json_str = "{\"name\":\"james\",\"sex\":\"boy\",\"age\":20}";					
char *str=NULL;
cJSON *cjson_data;
cJSON *cjson_str;
cjson_data = cJSON_Parse(json_str);//将json字符串转化成CJSON结构体类型的数据
if(cjson_data)
{
	cjson_str = cJSON_GetObjectItem(cjson_data,"name");//获取名称为name的值
	if(cjson_str)printf("%s:%s\r\n",cjson_str->string,cjson_str->valuestring);
    cjson_str = cJSON_GetObjectItem(cjson_data,"age");//获取名称为age的值
	if(cjson_str)printf("%s:%d\r\n",cjson_str->string,cjson_str->valueint);
	cJSON_Delete(cjson_data);
}

解析示例二:

json_str = "{ \
	             \"personA\":{\"name\":\"james\",\"sex\":\"boy\",\"age\":20},   \
				 \"personB\":{\"name\":\"joe\",\"sex\":\"girl\",\"age\":18}     \
	}";
int arr_size;

cjson_data = cJSON_Parse(json_str);//将json字符串转化成CJSON结构体类型的数据

if(!cjson_data)
{
	printf("json phase error\r\n");
	return;
}
printf("%d\r\n",cjson_data->type);

cJSON* personA = cJSON_GetObjectItem(cjson_data,"personA");;
//if(personA)printf("%s:%s\r\n",personA->string,personA->child->valuestring);
if(personA)
{	
	str = cJSON_Print(cJSON_GetObjectItem(personA,"name"));
	if(str)printf("name:%s\r\n",str);
	str = cJSON_Print(cJSON_GetObjectItem(personA,"sex"));
	if(str)printf("sex:%s\r\n",str);
	str = cJSON_Print(cJSON_GetObjectItem(personA,"age"));
	if(str)printf("age:%s\r\n",str);
	if(str)free(str);
}
else
{
	printf("personA phase error\r\n");
}
```c
创建json数据:

```c
cJSON *root;
cJSON *fmt;
cJSON *img;
cJSON *thm;
int ids[4]={116,943,234,38793};
char *out;

root=cJSON_CreateObject();
cJSON_AddItemToObject(root, "Image", img=cJSON_CreateObject());
cJSON_AddNumberToObject(img,"Width",800);
cJSON_AddNumberToObject(img,"Height",600);
cJSON_AddStringToObject(img,"Title","View from 15th Floor");
cJSON_AddItemToObject(img, "Thumbnail", thm=cJSON_CreateObject());
cJSON_AddStringToObject(thm, "Url", "http:/*www.example.com/image/481989943");
cJSON_AddNumberToObject(thm,"Height",125);
cJSON_AddStringToObject(thm,"Width","100");
cJSON_AddItemToObject(img,"IDs", cJSON_CreateIntArray(ids,4));

out=cJSON_Print(root);	cJSON_Delete(root);	printf("%s\n",out);	free(out);

cjson源码地址:https://sourceforge.net/projects/cjson/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值