当前位置:网站首页>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
边栏推荐
- Customize a loading instruction
- 【愚公系列】2022年07月 Go教学课程 001-Go语言前提简介
- UE4 draw a circle with spline
- Wechat nucleic acid detection appointment applet system graduation design completion (5) task statement
- Web聊天工具
- Picking up the camera is the best artistic healing
- A4988 and 42 stepper motors
- Leetcode interview question 16.11 Diving board
- 求求你们,别再刷 Star 了!这跟“爱国”没关系!
- 拿起相机,便是最好的艺术疗愈
猜你喜欢
如何开启IDEA的Run Dashboard功能
NVIDIA graphics card failed to initialize nvml driver/library version mismatch error solution
Uncover the whole link communication process of dewu customer service im
exness深度好文:动性系列-黄金流动性实例分析(五)
Leetcode 面试题 17.04. 消失的数字
Customize a loading instruction
Nm01 function overview and API definition of nm module independent of bus protocol
拿起相机,便是最好的艺术疗愈
Implementation shadow introduction
Leetcode interview question 17.01 Addition without plus sign
随机推荐
Nm01 function overview and API definition of nm module independent of bus protocol
Another double non reform exam 408, will it be cold? Software College of Nanchang Aviation University
Architecture design - ID generator "suggestions collection"
铁塔安全监测系统 无人值守倾角振动监测系统
微信核酸检测预约小程序系统毕业设计毕设(4)开题报告
RTE11- 中断解耦功能
Win10 uninstall CUDA
微信小程序视频分享平台系统毕业设计毕设(4)开题报告
Wechat applet video sharing platform system graduation design completion (4) opening report
Leetcode 面试题 16.11. 跳水板
Please, stop painting star! This has nothing to do with patriotism!
NVIDIA graphics card failed to initialize nvml driver/library version mismatch error solution
哪个券商公司网上开户佣金低又安全又可靠
Wechat applet video sharing platform system graduation design completion (8) graduation design thesis template
Leetcode interview question 16.17 Continuous sequence
MySQL installation and configuration
Ue4 dessine un cercle avec une ligne de contour
呆错图床系统源码图片CDN加速与破J防盗链功能
实施阴影介绍
Uncover the whole link communication process of dewu customer service im