当前位置:网站首页>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
边栏推荐
- Tower safety monitoring system unattended inclination vibration monitoring system
- Vimium mapping key
- 巴比特 | 元宇宙每日必读:一千块就能买一个虚拟主播?这是小企业的直播福音还是在“割韭菜”?...
- Wechat applet video sharing platform system graduation design completion (4) opening report
- Radian to angle, angle to radian in MATLAB
- 微信小程序视频分享平台系统毕业设计毕设(2)小程序功能
- Leetcode interview question 16.17 Continuous sequence
- Wechat nucleic acid detection and appointment applet system graduation design (3) background function
- Leetcode 面试题 16.15. 珠玑妙算
- UE4 draw a circle with spline
猜你喜欢

【西北工业大学】考研初试复试资料分享

UE4 用spline畫正圓

1288_ Implementation analysis of vtask resume() interface and interrupt Security version interface in FreeRTOS

Ue4 dessine un cercle avec une ligne de contour

Picking up the camera is the best artistic healing

Leetcode 面试题 16.17. 连续数列

pycharm 修改 pep8 E501 line too long > 0 characters

再放宽!这些应届生,可直接落户上海

Wechat applet video sharing platform system graduation design completion (1) development outline

Chrome 正式支持 MathML,默认在 Chromium Dev 105 中启用
随机推荐
Interview, about thread pool
Babbitt | metauniverse daily must read: can you buy a virtual anchor for 1000 yuan? Is this the live gospel of small businesses or "cutting leeks"
Paddlepaddle 28 build an automatic coder based on convolution
In early summer, Kaiyuan magic changed an electric mosquito racket with killing sound effect!
拿起相机,便是最好的艺术疗愈
能解决80%故障的排查思路
Détends - toi encore! Ces nouveaux étudiants peuvent s'installer directement à Shanghai
UE4 用spline画正圆
Leetcode 面试题 16.11. 跳水板
在支付宝账户上买基金安全吗
Mysql 备份的三种方式
Pit encountered during installation of laravel frame
QQmlApplicationEngine
Unity学习shader笔记[八十二]增强单通道颜色渲染的黑白处理
Is Guojin securities a state-owned enterprise? Is it safe to open an account in Guojin securities?
Export Excel files using npoi
阿里三面被面试官狂问Redis,简历上再也不敢写'精通'了
夜神模拟器+Fiddler抓包测试App
饭卡 HDU2546
StretchDIBits函数