当前位置:网站首页>Detailed explanation of cjson usage
Detailed explanation of cjson usage
2022-07-02 18:32:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm your friend, Quan Jun .
because c In language , There is no direct dictionary , String arrays and other data structures , So with the help of structure definition , Handle json. It is more convenient if there is a corresponding data structure , Such as python of use json.loads(json) Just put json It is convenient to convert strings into built-in data structures .
An important concept :
stay cjson in ,json The object can be json, Can be a string , It could be a number ...
cjson Data structure definition :
#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
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. cjson The type of the structure is defined by the macro above 7 One of them */
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;
#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
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. cjson The type of the structure is defined by the macro above 7 One of them */
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;
One 、 analysis json The function used , stay cJSON.h You can find it all in the library :
/* Supply a block of JSON, and this returns a cJSON object you can interrogate. Call cJSON_Delete when finished. */
extern cJSON *cJSON_Parse(const char *value);// from A given json Get from string cjson object
/* Render a cJSON entity to text for transfer/storage. Free the char* when finished. */
extern char *cJSON_Print(cJSON *item);// from cjson Object to get a formatted json object
/* Render a cJSON entity to text for transfer/storage without any formatting. Free the char* when finished. */
extern char *cJSON_PrintUnformatted(cJSON *item);// from cjson Object json object
/* Delete a cJSON entity and all subentities. */
extern void cJSON_Delete(cJSON *c);// Delete cjson object , Release the memory space occupied by the linked list
/* Returns the number of items in an array (or object). */
extern int cJSON_GetArraySize(cJSON *array);// obtain cjson Number of object array members
/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */
extern cJSON *cJSON_GetArrayItem(cJSON *array,int item);// Get... By subscript cjosn Objects in the object array
/* Get item "string" from object. Case insensitive. */
extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);// Get the corresponding value according to the key (cjson object )
/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
extern const char *cJSON_GetErrorPtr(void);// Get error string
To parse json
{
"semantic": {
"slots": {
"name": " Zhang San "
}
},
"rc": 0,
"operation": "CALL",
"service": "telephone",
"text": " Call Zhang San "
}
#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"
void printJson(cJSON * root)// Print recursively json The innermost key value pair of
{
for(int i=0; i<cJSON_GetArraySize(root); i++) // Traverse the outermost layer json Key value pair
{
cJSON * item = cJSON_GetArrayItem(root, i);
if(cJSON_Object == item->type) // If the value of the corresponding key is still cJSON_Object Call recursively printJson
printJson(item);
else // Values are not for json Objects print out keys and values directly
{
printf("%s->", item->string);
printf("%s\n", cJSON_Print(item));
}
}
}
int main()
{
char * jsonStr = "{\"semantic\":{\"slots\":{\"name\":\" Zhang San \"}}, \"rc\":0, \"operation\":\"CALL\", \"service\":\"telephone\", \"text\":\" Call Zhang San \"}";
cJSON * root = NULL;
cJSON * item = NULL;//cjson object
root = cJSON_Parse(jsonStr);
if (!root)
{
printf("Error before: [%s]\n",cJSON_GetErrorPtr());
}
else
{
printf("%s\n", " Print in a format Json:");
printf("%s\n\n", cJSON_Print(root));
printf("%s\n", " Print without format json:");
printf("%s\n\n", cJSON_PrintUnformatted(root));
printf("%s\n", " Step by step name Key value pair :");
printf("%s\n", " obtain semantic Under the cjson object :");
item = cJSON_GetObjectItem(root, "semantic");//
printf("%s\n", cJSON_Print(item));
printf("%s\n", " obtain slots Under the cjson object ");
item = cJSON_GetObjectItem(item, "slots");
printf("%s\n", cJSON_Print(item));
printf("%s\n", " obtain name Under the cjson object ");
item = cJSON_GetObjectItem(item, "name");
printf("%s\n", cJSON_Print(item));
printf("%s:", item->string); // to glance at cjson The meaning of these two members in the structure of the object
printf("%s\n", item->valuestring);
printf("\n%s\n", " Print json All innermost key value pairs :");
printJson(root);
}
return 0;
}
Two 、 structure json:
structure json Relatively simple , add to json Object can . I can see from the examples .
Mainly for ,cJSON_AddItemToObject Function add json node .
xtern cJSON *cJSON_CreateObject(void);
extern void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item);
extern cJSON *cJSON_CreateNull(void);
extern cJSON *cJSON_CreateTrue(void);
extern cJSON *cJSON_CreateFalse(void);
extern cJSON *cJSON_CreateBool(int b);
extern cJSON *cJSON_CreateNumber(double num);
extern cJSON *cJSON_CreateString(const char *string);
extern cJSON *cJSON_CreateArray(void);
extern cJSON *cJSON_CreateObject(void);
Example : To build json:
"semantic": {
"slots": {
"name": " Zhang San "
}
},
"rc": 0,
"operation": "CALL",
"service": "telephone",
"text": " Call Zhang San "
}
#include <stdio.h>
#include "cJSON.h"
int main()
{
cJSON * root = cJSON_CreateObject();
cJSON * item = cJSON_CreateObject();
cJSON * next = cJSON_CreateObject();
cJSON_AddItemToObject(root, "rc", cJSON_CreateNumber(0));// Add... Under the root node
cJSON_AddItemToObject(root, "operation", cJSON_CreateString("CALL"));
cJSON_AddItemToObject(root, "service", cJSON_CreateString("telephone"));
cJSON_AddItemToObject(root, "text", cJSON_CreateString(" Call Zhang San "));
cJSON_AddItemToObject(root, "semantic", item);//root Add under node semantic node
cJSON_AddItemToObject(item, "slots", next);//semantic Add under node item node
cJSON_AddItemToObject(next, "name", cJSON_CreateString(" Zhang San "));// add to name node
printf("%s\n", cJSON_Print(root));
return 0;
}
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/148422.html Link to the original text :https://javaforall.cn
边栏推荐
- win10 卸载cuda
- 1.5.1版本官方docker镜像运行容器,能设置使用 mysql 8驱动吗?
- Esp32-c3 introductory tutorial question ⑩ - error: implicit declaration of function 'ESP_ blufi_ close‘;
- 微信小程序视频分享平台系统毕业设计毕设(1)开发概要
- 能解决80%故障的排查思路
- Editor Editor Extension add button and logo in scene view
- 27:第三章:开发通行证服务:10:【注册/登录】接口:注册/登录OK后,把用户会话信息(uid,utoken)保存到redis和cookie中;(一个主要的点:设置cookie)
- RDK simulation experiment
- iptable端口重定向 MASQUERADE[通俗易懂]
- QT official example: QT quick controls - Gallery
猜你喜欢
MySQL installation and configuration
1288_ Implementation analysis of vtask resume() interface and interrupt Security version interface in FreeRTOS
Wechat applet video sharing platform system graduation design completion (6) opening defense ppt
夜神模拟器+Fiddler抓包测试App
夜神模擬器+Fiddler抓包測試App
Customize a loading instruction
Détends - toi encore! Ces nouveaux étudiants peuvent s'installer directement à Shanghai
微信小程序视频分享平台系统毕业设计毕设(8)毕业设计论文模板
UE4 draw a circle with spline
Leetcode 面试题 16.17. 连续数列
随机推荐
Ue4 dessine un cercle avec une ligne de contour
Chrome 正式支持 MathML,默认在 Chromium Dev 105 中启用
Meal card hdu2546
Nvidia 显卡 Failed to initialize NVML Driver/library version mismatch 错误解决方案
QQmlApplicationEngine
Relax again! These fresh students can settle directly in Shanghai
[Northwestern Polytechnic University] information sharing of the first and second postgraduate examinations
Architecture design - ID generator "suggestions collection"
服务器php环境搭建教程,PHP服务端环境搭建图文详解
In early summer, Kaiyuan magic changed an electric mosquito racket with killing sound effect!
Web聊天工具
Détends - toi encore! Ces nouveaux étudiants peuvent s'installer directement à Shanghai
Unity learning shader notes [82] black and white processing of enhanced single channel color rendering
Aptos教程-参与官方激励测试网(AIT2 激励测试网)
A4988与42步进电机
呆错图床系统源码图片CDN加速与破J防盗链功能
Aptos tutorial - participate in the official incentive testing network (ait2 incentive testing network)
matplotlib的安装教程以及简单调用
Typescript
Unity学习shader笔记[八十二]增强单通道颜色渲染的黑白处理