In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article focuses on "what is the use of JSON components", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what is the use of JSON components?"
1. JSON and cJSONJSON-lightweight data formats
JSON, whose full name is JavaScript Object Notation, or simplified spectrum of JS objects, is a lightweight data format.
It uses a text format that is completely independent of the programming language to store and represent data. The syntax is simple, the hierarchical structure is clear, and it is easy for people to read and write. At the same time, it is also easy for machine analysis and generation, which effectively improves the efficiency of network transmission.
JSON grammar rules
The JSON object is an unordered collection of name / value key-value pairs:
Starts with "{" and ends with "}", allowing nested use
Each name and value appear in pairs, separated by ":"
Key-value pairs are separated by ","
Allow meaningless white space before and after these characters
For key values, you can have the following values:
A new json object
Arrays: represented by "[" and "]"
Number: direct representation, either an integer or a floating point number
Strings: using quotation marks to indicate
Literal value: one of false, null, true (must be lowercase)
Examples are as follows:
{"name": "mculover666", "age": 22, "weight": 55.5 "address": {"country": "China", "zip-code": 111111}, "skill": ["c", "Java", "Python"], "student": false} cJSON components in LiteOS
CJSON is a JSON data parser written in C language, with ultra-portable, portable, single-file characteristics, using MIT open source protocol.
CJSON has been ported to LiteOS as a component. The source code is in sdk\ IoT_LINK_1.0.0\ iot_link\ cJSON, and there are only two source files:
CJSON.h
CJSON.c
When using it, you only need to copy these two files to the project directory, and then include the header file cJSON.h, as follows:
# include "cJSON.h" 2. CJSON data structure and design idea
The design idea of cJSON can be reflected in its data structure.
CJSON uses a cJSON structure to represent an JSON data, which is defined in cJSON.h. The source code is as follows:
/ * The cJSON structure: * / typedef struct cJSON {/ * next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem * / struct cJSON * next; struct cJSON * prev; / * An array or object item will have a child pointer pointing to a chain of the items in the array/object. * / struct cJSON * child; / * The type of the item, as above. * / int type; / * The item's string, if type==cJSON_String and type==cJSON_ Raw * / char * valuestring; / * writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead * / int valueint; / * The item's number, if type==cJSON_Number * / double valuedouble; / * The item's name string, if this item is the child of, or is in the list of subitems of an object. * / char * string;} cJSON
The design of cJSON is ingenious.
First of all, instead of abstracting an entire piece of JSON data, it abstracts a piece of JSON data, that is, a key-value pair, represented by the above structure strcut cJSON. The list of members used to store values is as follows:
String: the name used to represent the key-value pair
Type: the type used to represent the middle value of this key-value pair
Valuestring: if the key type (type) is a string, point the pointer to the key
Valueint: if the key type (type) is an integer, point the pointer to the key
Valuedouble: if the key value type (type) is a floating point number, point the pointer to the key value
Secondly, a complete piece of JSON data consists of many key-value pairs, and involves finding, deleting, and adding key-value pairs, so a linked list is used to store the entire piece of JSON data, as shown in the above code:
Next pointer: points to the next key-value pair
The prev pointer points to the previous key-value pair
Finally, because JSON data supports nesting, the value of a key-value pair can be a new JSON data object (a new linked list) or an array. For convenience, in cJSON, the array is also represented as an array object, stored in a linked list, so:
In the key-value pair structure, when the value of the key-value pair is a nested JSON data or an array, the child pointer points to the new linked list.
3. Open the cJSON component
In LiteOS, the cJSON component is not enabled by default and is enabled using the macro definition CONFIG_JSON_ENABLE.
When enabled, LiteOS will initialize automatically, and use the memory hook of cJSON to change the way cJSON applies for memory to use osal_malloc request. The automatic initialization code is in the link_main.c file:
4. JSON data encapsulation method
The process of encapsulating JSON data is actually the process of creating a linked list and adding nodes to it.
First, let's talk about some terms in the linked list:
Head pointer: a pointer to the header node of a chain
Head node: no valid data is stored, which is convenient for linked list operation.
First node: the first node to store valid data
Tail node: the last node to store valid data
With these concepts in mind, we begin to talk about creating a complete piece of JSON data, that is, how to create a complete linked list.
① creates a header pointer:
CJSON* cjson_test = NULL
② creates the header node and points the header pointer to the header node:
Cjson_test = cJSON_CreateObject ()
③ is free to add nodes to the linked list:
CJSON_AddNullToObject (cJSON * const object, const char * const name); cJSON_AddTrueToObject (cJSON * const object, const char * const name); cJSON_AddFalseToObject (cJSON * const object, const char * const name); cJSON_AddBoolToObject (cJSON * const object, const char * const name, const cJSON_bool boolean); cJSON_AddNumberToObject (cJSON * const object, const char * const name, const double number); cJSON_AddStringToObject (cJSON * const object, const char * const name, const char * const string) CJSON_AddRawToObject (cJSON * const object, const char * const name, const char * const raw); cJSON_AddObjectToObject (cJSON * const object, const char * const name); cJSON_AddArrayToObject (cJSON * const object, const char * const name); output JSON data
As mentioned above, a complete piece of JSON data is a long linked list, so how to print this piece of JSON data?
CJSON provides an API that outputs the JSON information stored in the entire linked list to a string:
(char *) cJSON_Print (const cJSON * item)
When using it, you only need to receive the pointer address returned by the function.
Example of encapsulated data and print data
The simple narrative method is not enough, the following example is used to illustrate the encapsulation of the JSON data given at the beginning.
First, based on the HelloWorld project, create a folder cloud_test_demo where the sample files are stored, and create a new experimental file cjson_print_demo.c, and write the following code:
# include # include # include static int cjson_print_demo_entry () {cJSON* cjson_test = NULL; cJSON* cjson_address = NULL; cJSON* cjson_skill = NULL; char* str = NULL; / * create a JSON data object (link header node) * / cjson_test = cJSON_CreateObject () / * add a JSON data of string type (add a linked list node) * / cJSON_AddStringToObject (cjson_test, "name", "mculover666"); / * add an integer type of JSON data (add a linked list node) * / cJSON_AddNumberToObject (cjson_test, "age", 22) / * add a floating point type of JSON data (add a linked list node) * / cJSON_AddNumberToObject (cjson_test, "weight", 55.5); / * add a nested JSON data (add a linked list node) * / cjson_address = cJSON_CreateObject (); cJSON_AddStringToObject (cjson_address, "country", "China"); cJSON_AddNumberToObject (cjson_address, "zip-code", 111111) CJSON_AddItemToObject (cjson_test, "address", cjson_address); / * add JSON data of an array type (add a linked list node) * / cjson_skill = cJSON_CreateArray (); cJSON_AddItemToArray (cjson_skill, cJSON_CreateString ("C")); cJSON_AddItemToArray (cjson_skill, cJSON_CreateString ("Java")); cJSON_AddItemToArray (cjson_skill, cJSON_CreateString ("Python")) CJSON_AddItemToObject (cjson_test, "skill", cjson_skill); / * add a Boolean type of JSON data with a value of False (add a linked list node) * / cJSON_AddFalseToObject (cjson_test, "student"); / * print all data of the JSON object (whole linked list) * / str = cJSON_Print (cjson_test); printf ("% s\ n", str) / * release the memory of the entire linked list * / cJSON_Delete (cjson_test); return 0;} int standard_app_demo_main () {osal_task_create ("cjson_print_demo", cjson_print_demo_entry,NULL,0x800,NULL,2); return 0;}
Configure the file path in user_demo.mk:
# example for cjson_print_demo ifeq ($(CONFIG_USER_DEMO), "cjson_print_demo") user_demo_src = ${wildcard $(TOP_DIR) / targets/STM32L431_BearPi/Demos/cloud_test_demo/cjson_print_demo.c} endif
The location is as follows:
Then open the cJSON component in .sdkconfig and select the demo:
The experimental results are as follows:
5. CJSON data parsing method
The process of parsing JSON data is actually the process of stripping a linked list node (key-value pair).
The parsing method is as follows:
① creates a chain header pointer:
CJSON* cjson_test = NULL
② parses the entire piece of JSON data and returns the address of the link header node, assigning a value to the header pointer:
Only one API is used to parse the entire piece of data:
(cJSON *) cJSON_Parse (const char * value)
③ takes the corresponding value from the linked list according to the name of the key-value pair and returns the address of the key-value pair (the linked list node).
(cJSON *) cJSON_GetObjectItem (const cJSON * const object, const char * const string)
④ if the value of the JSON data is an array, extract the data using the following two API:
(int) cJSON_GetArraySize (const cJSON * array); (cJSON *) cJSON_GetArrayItem (const cJSON * array, int index); parsing example
Here is an example of how to parse the JSON data given at the beginning.
In the folder cloud_test_demo where the sample files are stored, create a new experimental file, cjson_parse_demo.c, and write the following code:
# include # include # include char * message = "{\" name\ ":\" mculover666\ ",\\" age\ ": 22,\\" weight\ ": 55.5 \ "address\":\ {\ "country\":\ "China\",\\ "zip-code\": 111111\},\\ "skill\": [\ "c\",\ "Java\",\ "Python\"],\\ "student\": false\} " Static int cjson_test1_demo_entry () {cJSON* cjson_test = NULL; cJSON* cjson_name = NULL; cJSON* cjson_age = NULL; cJSON* cjson_weight = NULL; cJSON* cjson_address = NULL; cJSON* cjson_address_country = NULL; cJSON* cjson_address_zipcode = NULL; cJSON* cjson_skill = NULL; cJSON* cjson_student = NULL; int skill_array_size = 0, I = 0 CJSON* cjson_skill_item = NULL; / * parse entire pieces of JSO data * / cjson_test = cJSON_Parse (message); if (cjson_test = = NULL) {printf ("parse fail.\ n"); return-1;} / * extract JSON data according to name (key-value pair) * / cjson_name = cJSON_GetObjectItem (cjson_test, "name") Cjson_age = cJSON_GetObjectItem (cjson_test, "age"); cjson_weight = cJSON_GetObjectItem (cjson_test, "weight"); printf ("name:% s\ n", cjson_name- > valuestring); printf ("age:%d\ n", cjson_age- > valueint); printf ("weight:%.1f\ n", cjson_weight- > valuedouble) / * parsing nested json data * / cjson_address = cJSON_GetObjectItem (cjson_test, "address"); cjson_address_country = cJSON_GetObjectItem (cjson_address, "country"); cjson_address_zipcode = cJSON_GetObjectItem (cjson_address, "zip-code"); printf ("address-country:%s\ naddress-zipcode:%d\ n", cjson_address_country- > valuestring, cjson_address_zipcode- > valueint) / * parsing array * / cjson_skill = cJSON_GetObjectItem (cjson_test, "skill"); skill_array_size = cJSON_GetArraySize (cjson_skill); printf ("skill: ["); for (I = 0; I
< skill_array_size; i++) { cjson_skill_item = cJSON_GetArrayItem(cjson_skill, i); printf("%s,", cjson_skill_item->Valuestring);} printf ("\ b]\ n"); / * parsing Boolean data * / cjson_student = cJSON_GetObjectItem (cjson_test, "student"); if (cjson_student- > valueint = = 0) {printf ("student: false\ n");} else {printf ("student:error\ n") } / * release the memory of the entire linked list * / cJSON_Delete (cjson_test); return 0;} int standard_app_demo_main () {osal_task_create ("cjson_test1_demo", cjson_test1_demo_entry,NULL,0x800,NULL,2); return 0;}
Configure the file path in user_demo.mk:
# example for cjson_parse_demo ifeq ($(CONFIG_USER_DEMO), "cjson_parse_demo") user_demo_src = ${wildcard $(TOP_DIR) / targets/STM32L431_BearPi/Demos/cloud_test_demo/cjson_parse_demo.c} endif
The location is as follows:
Then open the cJSON component in .sdkconfig and select the demo:
The experimental results are as follows:
Matters needing attention
In this example, because I know the type of data in advance, such as character type or floating point type, I directly use the pointer to point to the corresponding data field extraction. In actual use, if the data type is not determined in advance, I should first judge the value of type, determine the data type, and then extract data from the corresponding data field.
6. Memory problems during the use of cJSON memory is released in time
All operations of cJSON are based on linked lists, so cJSON uses malloc to allocate dynamic memory from the heap during its use. Therefore, after using it, you should call the following function in time to empty the memory pointed to by the cJSON pointer, which can also be used to delete a certain piece of data:
(void) cJSON_Delete (cJSON * item)
Note: when this function deletes a piece of JSON data, it will be deleted if it is nested.
Memory hook
CJSON supports custom malloc and free functions as follows:
① uses cJSON_Hooks to connect custom malloc and free functions:
Typedef struct cJSON_Hooks {/ * malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. * / void * (CJSON_CDECL * malloc_fn) (size_t sz); void (CJSON_CDECL * free_fn) (void * ptr);} cJSON_Hooks
② initialize hook cJSON_Hooks
(void) cJSON_InitHooks (cJSON_Hooks* hooks); at this point, I believe you have a better understanding of "what is the use of JSON components". You might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.