Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use CJSON in Cracket +

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

The purpose of this article is to share with you the content about how to use CJSON in CAccord Candle +. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

1. Introduction of cJSON

CJSON is an ultra-lightweight, easy to carry, single file, can be used as an ANSI-C standard JSON parser, is a C language to write a simple and easy to use JSON parser; it only contains a C file and a header file, can be easily integrated into their own projects.

And cJSON is written in ANSI C (C89) and is compatible with all platforms and compilers that support the C language.

CJSON download address: https://sourceforge.net/projects/cjson/

CJSON's GitHub warehouse address: https://github.com/DaveGamble/cJSON

Second, JSON introduction, grammar introduction 2.1What is JSON?

JSON is JavaScript Object Notation (JavaScript object representation), which is a lightweight data exchange format.

JSON is mainly used to store and exchange text information, similar to XML format; but JSON is smaller, faster, and easier to parse than XML.

JSON is based on a subset of ECMAScript (the js specification developed by the European computer Association) and uses a text format that is completely independent of the programming language to store and represent data.

The concise and clear hierarchical structure makes JSON an ideal data exchange language. It is easy for people to read and write, at the same time, it is also easy for machine analysis and generation, and effectively improve the efficiency of network transmission. For example: Web server interfaces basically use JSON feedback data, using JSON format string to describe character information. JSON files are usually suffixed with .json, which is just for ease of identification.

To put it simply, JSON is a string serialized according to the specified format, and even if you don't use any ready-made parsing library, you can parse the string normally; there is a ready-made standard JSON parsing library, which greatly reduces our workload.

Example of data in JSON format: this is a JSON string representing the current time

{"success": "1", "result": {"timestamp": "1631849514", "datetime_1": "2021-09-17 20:31:54", "datetime_2": "20:31:54 on September 17, 2021", "week_1": "5", "week_2": "Friday", "week_3": "Friday", "week_4": "Friday"}}

Example of data in JSON format: this is a json string representing the weather forecast for the next few days

{"success": "1", "result": [{"weaid": "1", "days": "2021-09-17", "week": "Friday", "cityno": "beijing", "citynm": "Beijing", "cityid": "101010100", "temperature": "26 ℃ / 17 ℃", "humidity": "0% ℃" "weather": "Qing", "weather_icon": "http://api.k780.com/upload/weather/d/0.gif"," weather_icon1 ":" http://api.k780.com/upload/weather/n/0.gif", "wind": "north wind to southwest wind", "winp": "less than 3", "temp_high": "26" "temp_low": "17", "humi_high": "0", "humi_low": "0", "weatid": "1", "weatid1": "1", "windid": "8", "winpid": "0", "weather_iconid": "0", "weather_iconid1": "0"} {"weaid": "1", "days": "2021-09-18", "week": "Saturday", "cityno": "beijing", "citynm": "Beijing", "cityid": "101010100", "temperature": "25 ℃ / 17 ℃", "humidity": "0% temperature", "weather": "cloudy" "weather_icon": "http://api.k780.com/upload/weather/d/1.gif"," weather_icon1 ":" http://api.k780.com/upload/weather/n/1.gif", "wind": "Southwest Wind", "winp": "below Category 3", "temp_high": "25", "temp_low": "17" "humi_high": "0", "humi_low": "0", "weatid": "2", "weatid1": "2", "windid": "5", "winpid": "0", "weather_iconid": "1", "weather_iconid1": "1"}, {"weaid": "1" "days": "2021-09-19", "week": "Sunday", "cityno": "beijing", "citynm": "Beijing", "cityid": "101010100", "temperature": "19 ℃ / 15 ℃", "humidity": "0% ℃", "weather": "light rain to moderate rain" "weather_icon": "http://api.k780.com/upload/weather/d/7.gif"," weather_icon1 ":" http://api.k780.com/upload/weather/n/8.gif", "wind": "Southwest Wind to North Wind", "winp": "from less than 3 to less than 3", "temp_high": "19", "temp_low": "15" "humi_high": "0", "humi_low": "0", "weatid": "8", "weatid1": "9", "windid": "5", "winpid": "0", "weather_iconid": "7", "weather_iconid1": "8"}, {"weaid": "1" "days": "2021-09-20", "week": "Monday", "cityno": "beijing", "citynm": "Beijing", "cityid": "101010100", "temperature": "26 ℃ / 16 ℃", "humidity": "0% ℃", "weather": "cloudy to sunny" "weather_icon": "http://api.k780.com/upload/weather/d/1.gif"," weather_icon1 ":" http://api.k780.com/upload/weather/n/0.gif", "wind": "North Wind", "winp": "3-4 to 3-4", "temp_high": "26", "temp_low": "16" "humi_high": "0", "humi_low": "0", "weatid": "2", "weatid1": "1", "windid": "8", "winpid": "1", "weather_iconid": "1", "weather_iconid1": "0"}, {"weaid": "1" "days": "2021-09-21", "week": "Tuesday", "cityno": "beijing", "citynm": "Beijing", "cityid": "101010100", "temperature": "27 ℃ / 16 ℃", "humidity": "0% humidity", "weather": "Qing" "weather_icon": "http://api.k780.com/upload/weather/d/0.gif"," weather_icon1 ":" http://api.k780.com/upload/weather/n/0.gif", "wind": "northwest wind to north wind", "winp": "less than Category 3", "temp_high": "27", "temp_low": "16" "humi_high": "0", "humi_low": "0", "weatid": "1", "weatid1": "1", "windid": "7", "winpid": "0", "weather_iconid": "0", "weather_iconid1": "0"}, {"weaid": "1" "days": "2021-09-22", "week": "Wednesday", "cityno": "beijing", "citynm": "Beijing", "cityid": "101010100", "temperature": "26 ℃ / 18 ℃", "humidity": "0% ℃", "weather": "cloudy" "weather_icon": "http://api.k780.com/upload/weather/d/1.gif"," weather_icon1 ":" http://api.k780.com/upload/weather/n/1.gif", "wind": "North wind to northeast wind", "winp": "less than Category 3", "temp_high": "26", "temp_low": "18" "humi_high": "0", "humi_low": "0", "weatid": "2", "weatid1": "2", "windid": "8", "winpid": "0", "weather_iconid": "1", "weather_iconid1": "1"}, {"weaid": "1" "days": "2021-09-23", "week": "Thursday", "cityno": "beijing", "citynm": "Beijing", "cityid": "101010100", "temperature": "24 ℃ / 16 ℃", "humidity": "0% ℃", "weather": "cloudy" "weather_icon": "http://api.k780.com/upload/weather/d/1.gif"," weather_icon1 ":" http://api.k780.com/upload/weather/n/1.gif", "wind": "Northeast Wind", "winp": "less than level 3", "temp_high": "24", "temp_low": "16" "humi_high": "0", "humi_low": "0", "weatid": "2", "weatid1": "2", "windid": "1", "winpid": "0", "weather_iconid": "1", "weather_iconid1": "1"} 2.2 JSON grammar introduction

There are two kinds of structures in JSON: objects and arrays, through which various complex structures can be represented.

JSON grammar rules

1. Curly braces {} are used to save objects

two。 Brackets [] are used to hold arrays. Arrays can also contain multiple objects, and objects can contain arrays that can be nested.

3. The value of JSON indicates syntax: key: value-- > "width": 1280

4. Multiple data is separated by commas: {"width": 1920, "height": 1080}

JSON values can be of the following types:

1. Number (integer or floating point)

two。 String (in double quotes)

3. Logical value (true or false)

4. Array (in square brackets)

5. Object (in curly braces)

6. Null (null)

3. CJSON creates simple JSON data and parses 3.1 new project

This is the downloaded cJSON source file, you can add it to your own project.

I use VS2017 here to build a project and demonstrate an example.

After the project is completed, add the file to the project:

The string processing function of C language in VS2017 will report an error and indicate that it is not safe.

1 > d:\ linux-share-dir\ vs2017\ console_cjsontest\ console_cjsontest\ cjson.c (155): error C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _ CRT_SECURE_NO_WARNINGS. See online help for details.

The solution is to find [Project Properties], click "preprocessor" in [C++], edit the "preprocessor", and add a code: _ CRT_SECURE_NO_WARNINGS to it.

3.2Creating JSON data

The next goal is to use cJSON to create the following data in JSON format:

{"text": "I am a string data", "number": 666, "state1": false, "state2": true, "state3": null}

The sample code is as follows:

# include / / because the current project uses cpp suffix files, files referencing C language need to extern "C" {# include # include # include "cJSON.h"} int main () {/ / 1. Create a cJSON object cJSON* root = cJSON_CreateObject (); / / 2. Create data cJSON_AddStringToObject (root, "text", "I am a string data"); cJSON_AddNumberToObject (root, "number", 666); cJSON_AddBoolToObject (root, "state1", cJSON_False); cJSON_AddBoolToObject (root, "state2", cJSON_True); cJSON_AddNullToObject (root, "state3"); / / 3. Print the resulting result char * json_data=cJSON_PrintUnformatted (root); printf ("% s\ n", json_data); / / 4. Free space cJSON_Delete (root); return 0;}

Parsing JSON data # include / / because the current project uses cpp suffix files, files referencing C language need to use the following way to extern "C" {# include # include # include "cJSON.h"} / / the JSON data to be parsed. Char data [] = "{"\ "text\":\ "I am a string data\", "\" number\ ": 666,"\ "state1\": false, ""\ "state2\": true, ""\ "state3\": null ""} "; int main () {/ / 1. Load JSON data cJSON* root = cJSON_Parse (data); if (root = = NULL) return 0; / / 2. Parse fields cJSON* item; item=cJSON_GetObjectItem (root, "text"); if (item) {printf ("text=%s\ n", item- > valuestring);} item=cJSON_GetObjectItem (root, "number"); if (item) {printf ("text=%d\ n", item- > valueint) } item = cJSON_GetObjectItem (root, "state1"); if (item) {printf ("state1=%d\ n", item- > valueint);} item = cJSON_GetObjectItem (root, "state2"); if (item) {printf ("state2=%d\ n", item- > valueint) } item = cJSON_GetObjectItem (root, "state3"); if (item) {printf ("state3=%d\ n", item- > valueint);} / / 3. Free space cJSON_Delete (root); return 0;}

4. CJSON creates nested object data

Goal: use cJSON to create the following data in JSON format

{"data1": {"text": "I am a string data 1", "number": 666, "state1": false, "state2": true, "state3": null}, "data2": {"text": "I am a string data 2", "number": 666, "state1": false, "state2": true "state3": null}} 4.1 create json data # include / / because the current project uses a cpp suffix file, files referencing C language need to extern "C" {# include # include # include "cJSON.h"} int main () {/ / 1. Create a cJSON object cJSON* root = cJSON_CreateObject (); / / 2. Create object data 1 cJSON* item1 = cJSON_CreateObject (); cJSON_AddStringToObject (item1, "text", "I am a string data 1"); cJSON_AddNumberToObject (item1, "number", 666); cJSON_AddBoolToObject (item1, "state1", cJSON_False); cJSON_AddBoolToObject (item1, "state2", cJSON_True); cJSON_AddNullToObject (item1, "state3") CJSON_AddItemToObject (root, data1, item1) / / 3. Create object data 2 cJSON* item2 = cJSON_CreateObject (); cJSON_AddStringToObject (item2, "text", "I am a string data 2"); cJSON_AddNumberToObject (item2, "number", 666); cJSON_AddBoolToObject (item2, "state1", cJSON_False); cJSON_AddBoolToObject (item2, "state2", cJSON_True); cJSON_AddNullToObject (item2, "state3") CJSON_AddItemToObject (root, data2, item2) / / 3. Print the resulting result char * json_data=cJSON_PrintUnformatted (root); printf ("% s\ n", json_data); / / 4. Free space cJSON_Delete (root); return 0;} 4.2 parse JSON data # include / / because the current project uses a cpp suffix file, files referencing C language need to extern "C" {# include # include # include "cJSON.h"} / / the JSON data to be parsed. Char data [] = "{"\ "data1\": {""\ "text\":\ "I am a string data 1\", "\" number\ ": 666,"\" state1\ ": false,"\" state2\ ": true,"\" state3\ ": null"}" ""\ "data2\": {""\ "text\":\ "I am a string data 2\", "\" number\ ": 666,"\" state1\ ": false,"\" state2\ ": true,"\" state3\ ": null"} "}" Int main () {/ / 1. Load JSON data cJSON* root = cJSON_Parse (data); if (root = = NULL) return 0; / / 2. Parse fields cJSON* item; item=cJSON_GetObjectItem (root, "data1"); if (item) {cJSON* obj; obj=cJSON_GetObjectItem (item, "text"); if (obj) {printf ("text=%s\ n", obj- > valuestring) } obj=cJSON_GetObjectItem (item, "number"); if (obj) {printf ("number=%d\ n", obj- > valueint);} obj=cJSON_GetObjectItem (item, "state1") If (obj) {printf ("state1=%d\ n", obj- > valueint);} obj = cJSON_GetObjectItem (item, "state2"); if (obj) {printf ("state2=%d\ n", obj- > valueint) } obj = cJSON_GetObjectItem (item, "state3"); if (obj) {printf ("state3=%d\ n", obj- > valueint);}} item = cJSON_GetObjectItem (root, "data2") If (item) {cJSON * obj; obj = cJSON_GetObjectItem (item, "text"); if (obj) {printf ("text=%s\ n", obj- > valuestring);} obj = cJSON_GetObjectItem (item, "number") If (obj) {printf ("number=%d\ n", obj- > valueint);} obj = cJSON_GetObjectItem (item, "state1"); if (obj) {printf ("state1=%d\ n", obj- > valueint) } obj = cJSON_GetObjectItem (item, "state2"); if (obj) {printf ("state2=%d\ n", obj- > valueint);} obj = cJSON_GetObjectItem (item, "state3") If (obj) {printf ("state3=%d\ n", obj- > valueint);} / / 3. Free space cJSON_Delete (root); return 0;}

5. CJSON JSON data with array

Goal: use cJSON to create the following data in JSON format

{"text": [{"width": 1280, "height": 720}, {"width": 1920, "height": 1080}, {"width": 3840, "height": 2160}]} 5.1 create json data # include / / because the cpp suffix file is used in the current project Files referencing C need to use the following way to extern "C" {# include # include # include "cJSON.h"} int main () {cJSON * width = NULL CJSON * height = NULL; int i; const unsigned int resolution_numbers [3] [2] = {1280}, {1920, 1080}, {3840, 2160}}; / / 1. Create a cJSON object cJSON* root = cJSON_CreateObject (); / / 2. Create array objects cJSON * array = cJSON_CreateArray (); cJSON_AddItemToObject (root, "text", array); for (I = 0; I

< (sizeof(resolution_numbers) / (2 * sizeof(int))); ++i) { cJSON *obj = cJSON_CreateObject(); cJSON_AddItemToArray(array, obj); width = cJSON_CreateNumber(resolution_numbers[i][0]); cJSON_AddItemToObject(obj, "width", width); height = cJSON_CreateNumber(resolution_numbers[i][1]); cJSON_AddItemToObject(obj, "height", height); } //3. 打印生成的结果 char *json_data=cJSON_PrintUnformatted(root); printf("%s\n",json_data); //4. 释放空间 cJSON_Delete(root); return 0;}5.2 解析JSON数据#include //因为当前工程使用的是cpp后缀文件,引用C语言的文件需要使用下面的这种方式extern "C" {#include #include #include "cJSON.h"} //将要解析的JSON数据. char data[] ="{""\"text\": [""{""\"width\": 1280,""\"height\" : 720""},""{""\"width\": 1920,""\"height\" : 1080""},""{""\"width\": 3840,""\"height\" : 2160""}""]""}"; int main(){ //1. 载入JSON数据 cJSON* root = cJSON_Parse(data); if (root == NULL)return 0; //2. 解析字段 cJSON* item; int i; item = cJSON_GetObjectItem(root, "text"); if (item) { //获取数组的大小 int ArraySize = cJSON_GetArraySize(item); //解析数组的里的每个成员 for (i = 0; i < ArraySize; i++) { //取出数组下标对象 cJSON *array_item = cJSON_GetArrayItem(item, i); if (array_item == NULL)continue; //解析数据 cJSON *obj = cJSON_GetObjectItem(array_item, "width"); if (obj) { printf("width=%d\n",obj->

Valueint);} obj = cJSON_GetObjectItem (array_item, "height"); if (obj) {printf ("height=%d\ n", obj- > valueint) } / / 3. Free space cJSON_Delete (root); return 0;}

Thank you for reading! This is the end of the article on "how to use CJSON in Cplink +". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report