cJSON使用说明
1.下载链接
DaveGamble/cJSON:ANSI C 语言中的超轻量级 JSON 解析器
GitHub - DaveGamble/cJSON: Ultralightweight JSON parser in ANSI C
git clone https://github.com/DaveGamble/cJSON.git
2.只需导入
cJSON/cJSON.c cJSON/cJSON.h
3.API讲解
/* cJSON Types: */ #define cJSON_Invalid (0) #define cJSON_False (1 << 0) #define cJSON_True (1 << 1) #define cJSON_NULL (1 << 2) #define cJSON_Number (1 << 3) #define cJSON_String (1 << 4) #define cJSON_Array (1 << 5) #define cJSON_Object (1 << 6) #define cJSON_Raw (1 << 7) /* raw json */ #define cJSON_IsReference 256 #define cJSON_StringIsConst 512 /* 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; 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; typedef int cJSON_bool; /* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them. * This is to prevent stack overflows. */ #ifndef CJSON_NESTING_LIMIT #define CJSON_NESTING_LIMIT 1000 #endif /* Limits the length of circular references can be before cJSON rejects to parse them. * This is to prevent stack overflows. */ #ifndef CJSON_CIRCULAR_LIMIT #define CJSON_CIRCULAR_LIMIT 10000 #endif /* returns the version of cJSON as a string */ CJSON_PUBLIC(const char*) cJSON_Version(void); /* Supply malloc, realloc and free functions to cJSON */ CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks); /* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */ /* Supply a block of JSON, and this returns a cJSON object you can interrogate. */ CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value); CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length); /* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */ /* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */ CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated); CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated); /* Render a cJSON entity to text for transfer/storage. */ CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item); /* Render a cJSON entity to text for transfer/storage without any formatting. */ CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item); /* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */ CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt); /* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */ /* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */ CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format); /* Delete a cJSON entity and all subentities. */ CJSON_PUBLIC(void) cJSON_Delete(cJSON *item); /* Returns the number of items in an array (or object). */ CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array); /* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */ CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index); /* Get item "string" from object. Case insensitive. */ CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string); CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string); CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string); /* 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. */ CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void); /* Check item type and return its value */ CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item); CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item); /* These functions check the type of an item */ CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item); CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item); CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item); CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item); CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item); CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item); CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item); CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item); CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item); CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item); /* These calls create a cJSON item of the appropriate type. */ CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void); CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void); CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void); CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean); CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num); CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string); /* raw json */ CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw); CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void); CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void); /* Create a string where valuestring references a string so * it will not be freed by cJSON_Delete */ CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string); /* Create an object/array that only references it's elements so * they will not be freed by cJSON_Delete */ CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child); CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child); /* These utilities create an Array of count items. * The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/ CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count); CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count); CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count); CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count); /* Append item to the specified array/object. */ CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item); CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item); /* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object. * WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before * writing to `item->string` */ CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item); /* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */ CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item); CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item); /* Remove/Detach items from Arrays/Objects. */ CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item); CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which); CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which); CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string); CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string); CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string); CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string); /* Update array items. */ CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */ CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement); CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem); CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem); CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem); /* Duplicate a cJSON item */ CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse); /* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will * need to be released. With recurse!=0, it will duplicate any children connected to the item. * The item->next and ->prev pointers are always zero on return from Duplicate. */ /* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal. * case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */ CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive); /* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings. * The input pointer json cannot point to a read-only address area, such as a string constant, * but should point to a readable and writable address area. */ CJSON_PUBLIC(void) cJSON_Minify(char *json); /* Helper functions for creating and adding items to an object at the same time. * They return the added item or NULL on failure. */ CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name); CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name); CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name); CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean); CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number); CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string); CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw); CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name); CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name); /* When assigning an integer value, it needs to be propagated to valuedouble too. */ #define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number)) /* helper for the cJSON_SetNumberValue macro */ CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number); #define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number)) /* Change the valuestring of a cJSON_String object, only takes effect when type of object is cJSON_String */ CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring); /* If the object is not a boolean type this does nothing and returns cJSON_Invalid else it returns the new type*/ #define cJSON_SetBoolValue(object, boolValue) ( \ (object != NULL && ((object)->type & (cJSON_False|cJSON_True))) ? \ (object)->type=((object)->type &(~(cJSON_False|cJSON_True)))|((boolValue)?cJSON_True:cJSON_False) : \ cJSON_Invalid\ ) /* Macro for iterating over an array or object */ #define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next) /* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */ CJSON_PUBLIC(void *) cJSON_malloc(size_t size); CJSON_PUBLIC(void) cJSON_free(void *object);
4.使用
4.1 cJSON_Parse
CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value); CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length); /* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */ /* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */ CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated); CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated);
4.2 cJSON_Print
/* Render a cJSON entity to text for transfer/storage. */ CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item); /* Render a cJSON entity to text for transfer/storage without any formatting. */ CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item); /* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */ CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt); /* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */ /* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */ CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format);
4.2.1 cJSON_Print
#include <stdio.h> #include <cjson/cjson.h> int main() { cJSON *root = cJSON_CreateObject(); cJSON_AddItemToObject(root, "name", cJSON_CreateString("John")); cJSON_AddItemToObject(root, "age", cJSON_CreateNumber(30)); char *json_string = cJSON_Print(root); printf("%s\n", json_string); // 释放内存 cJSON_free(root); free(json_string); return 0; }
4.2.2 cJSON_PrintUnformatted
#include <stdio.h> #include <cjson/cjson.h> int main() { cJSON *root = cJSON_CreateObject(); cJSON_AddItemToObject(root, "name", cJSON_CreateString("John")); cJSON_AddItemToObject(root, "age", cJSON_CreateNumber(30)); char *json_string = cJSON_PrintUnformatted(root); printf("%s\n", json_string); cJSON_free(root); free(json_string); return 0; }
4.2.3 cJSON_PrintBuffered
#include <stdio.h> #include <cjson/cjson.h> int main() { cJSON *root = cJSON_CreateObject(); // 假设这里添加了大量的键值对到root对象中 // 预估字符串大小为1024字节 int prebuffer = 1024; char *json_string = cJSON_PrintBuffered(root, prebuffer, 1); printf("%s\n", json_string); cJSON_free(root); free(json_string); return 0; }
4.2.4 cJSON_PrintPreallocated
#include <stdio.h> #include <cjson/cjson.h> int main() { cJSON *root = cJSON_CreateObject(); cJSON_AddItemToObject(root, "name", cJSON_CreateString("John")); cJSON_AddItemToObject(root, "age", cJSON_CreateNumber(30)); // 假设预先分配了200字节的缓冲区 char buffer[200]; cJSON_bool success = cJSON_PrintPreallocated(root, buffer, sizeof(buffer), 1); if (success) { printf("%s\n", buffer); } else { printf("Error: Failed to print cJSON to preallocated buffer.\n"); } cJSON_free(root); return 0; }
4.3
4.3.1 cJSON_Delete
#include <stdio.h> #include "cJSON.h" int main() { const char *json_string = "{\"name\":\"John\", \"age\":30}"; cJSON *root = cJSON_Parse(json_string); if (root) { // 在这里可以对解析后的JSON数据进行操作 //... // 操作完成后,删除整个JSON结构 cJSON_Delete(root); } return 0; }
4.3.2 cJSON_GetArraySize
#include <stdio.h> #include "cJSON.h" int main() { const char *json_string = "[1, 2, 3, 4, 5]"; cJSON *root = cJSON_Parse(json_string); if (root && cJSON_IsArray(root)) { int size = cJSON_GetArraySize(root); for (int i = 0; i < size; i++) { cJSON *item = cJSON_GetArrayItem(root, i); if (cJSON_IsNumber(item)) { printf("%d ", item->valueint); } } cJSON_Delete(root); } return 0; }
4.3.3 cJSON_GetArrayItem
#include <stdio.h> #include "cJSON.h" int main() { const char *json_string = "[\"apple\", \"banana\", \"cherry\"]"; cJSON *root = cJSON_Parse(json_string); if (root && cJSON_IsArray(root)) { cJSON *item = cJSON_GetArrayItem(root, 1); if (item) { printf("The second item in the array is: %s\n", item->valuestring); } cJSON_Delete(root); } return 0; }
4.3.4 cJSON_GetObjectItem
#include <stdio.h> #include "cJSON.h" int main() { const char *json_string = "{\"NaMe\":\"John\", \"AGE\":30}"; cJSON *root = cJSON_Parse(json_string); if (root && cJSON_IsObject(root)) { cJSON *name = cJSON_GetObjectItem(root, "name"); if (name) { printf("Name: %s\n", name->valuestring); } cJSON_Delete(root); } return 0; }
4.3.5 cJSON_GetObjectItemCaseSensitive
#include <stdio.h> #include "cJSON.h" int main() { const char *json_string = "{\"Name\":\"John\", \"Age\":30}"; cJSON *root = cJSON_Parse(json_string); if (root && cJSON_IsObject(root)) { cJSON *name = cJSON_GetObjectItemCaseSensitive(root, "Name"); if (name) { printf("Name: %s\n", name->valuestring); } cJSON_Delete(root); } return 0; }
4.3.6 cJSON_HasObjectItem
#include <stdio.h> #include "cJSON.h" int main() { const char *json_string = "{\"name\":\"John\", \"age\":30}"; cJSON *root = cJSON_Parse(json_string); if (root && cJSON_IsObject(root)) { if (cJSON_HasObjectItem(root, "name")) { cJSON *name = cJSON_GetObjectItem(root, "name"); printf("Name: %s\n", name->valuestring); } cJSON_Delete(root); } return 0; }
4.3.7 cJSON_GetErrorPtr
#include <stdio.h> #include "cJSON.h" int main() { const char *json_string = "{\"name\":\"John\", \"age\":30";// 这里故意缺少一个右花括号 cJSON *root = cJSON_Parse(json_string); if (!root) { const char *error_ptr = cJSON_GetErrorPtr(); if (error_ptr) { fprintf(stderr, "Error before: %s\n", error_ptr); } } return 0; }
4.4
4.4.1 cJSON_GetStringValue
#include <stdio.h> #include "cJSON.h" int main() { const char *json_string = "{\"name\":\"John\"}"; cJSON *root = cJSON_Parse(json_string); if (root && cJSON_IsObject(root)) { cJSON *name_item = cJSON_GetObjectItem(root, "name"); if (name_item) { char *name = cJSON_GetStringValue(name_item); if (name) { printf("The name is: %s\n", name); } } cJSON_Delete(root); } return 0; }
4.4.2 cJSON_GetNumberValue
#include <stdio.h> #include "cJSON.h" int main() { const char *json_string = "{\"age\":30}"; cJSON *root = cJSON_Parse(json_string); if (root && cJSON_IsObject(root)) { cJSON *age_item = cJSON_GetObjectItem(root, "age"); if (age_item) { double age = cJSON_GetNumberValue(age_item); printf("The age is: %.0f\n", age); } cJSON_Delete(root); } return 0; }
4.4.3 cJSON_IsInvalid
#include <stdio.h> #include "cJSON.h" int main() { const char *json_string = "{\"name\":\"John\", \"age\":30";// 这里故意造成解析错误 cJSON *root = cJSON_Parse(json_string); if (cJSON_IsInvalid(root)) { printf("The cJSON structure is invalid.\n"); } else { // 如果有效则进行正常操作 //... cJSON_Delete(root); } return 0; }
4.4.4 cJSON_IsFalse
#include <stdio.h> #include "cJSON.h" int main() { const char *json_string = "{\"is_active\": false}"; cJSON *root = cJSON_Parse(json_string); if (root && cJSON_IsObject(root)) { cJSON *is_active_item = cJSON_GetObjectItem(root, "is_active"); if (cJSON_IsFalse(is_active_item)) { printf("The flag is false.\n"); } cJSON_Delete(root); } return 0; }
4.4.5 cJSON_IsTrue
#include <stdio.h> #include "cJSON.h" int main() { const char *json_string = "{\"is_enabled\": true}"; cJSON *root = cJSON_Parse(json_string); if (root && cJSON_IsObject(root)) { cJSON *is_enabled_item = cJSON_GetObjectItem(root, "is_enabled"); if (cJSON_IsTrue(is_enabled_item)) { printf("The flag is true.\n"); } cJSON_Delete(root); } return 0; }
4.4.6 cJSON_IsBool
#include <stdio.h> #include "cJSON.h" int main() { const char *json_string = "{\"is_admin\": true, \"name\":\"John\"}"; cJSON *root = cJSON_Parse(json_string); if (root && cJSON_IsObject(root)) { cJSON *is_admin_item = cJSON_GetObjectItem(root, "is_admin"); if (cJSON_IsBool(is_admin_item)) { if (cJSON_IsTrue(is_admin_item)) { printf("The user is an admin.\n"); } else { printf("The user is not an admin.\n"); } } cJSON_Delete(root); } return 0; }
4.4.7 cJSON_IsNull
#include <stdio.h> #include "cJSON.h" int main() { const char *json_string = "{\"address\": null, \"name\":\"John\"}"; cJSON *root = cJSON_Parse(json_string); if (root && cJSON_IsObject(root)) { cJSON *address_item = cJSON_GetObjectItem(root, "address"); if (cJSON_IsNull(address_item)) { printf("The address is null.\n"); } cJSON_Delete(root); } return 0; }
4.4.8 cJSON_IsNumber
#include <stdio.h> #include "cJSON.h" int main() { const char *json_string = "{\"price\": 10.5, \"name\":\"Product\"}"; cJSON *root = cJSON_Parse(json_string); if (root && cJSON_IsObject(root)) { cJSON *price_item = cJSON_GetObjectItem(root, "price"); if (cJSON_IsNumber(price_item)) { double price = cJSON_GetNumberValue(price_item); printf("The price is: %.2f\n", price); } cJSON_Delete(root); } return 0; }
4.4.9 cJSON_IsString
#include <stdio.h> #include "cJSON.h" int main() { const char *json_string = "{\"description\": \"This is a product\", \"id\":1}"; cJSON *root = cJSON_Parse(json_string); if (root && cJSON_IsObject(root)) { cJSON *description_item = cJSON_GetObjectItem(root, "description"); if (cJSON_IsString(description_item)) { char *description = cJSON_GetStringValue(description_item); printf("The description is: %s\n", description); } cJSON_Delete(root); } return 0; }
4.4.10 cJSON_IsArray
#include <stdio.h> #include "cJSON.h" int main() { const char *json_string = "{\"products\":[{\"name\":\"Product1\", \"price\":10}, {\"name\":\"Product2\", \"price\":20}]}"; cJSON *root = cJSON_Parse(json_string); if (root && cJSON_IsObject(root)) { cJSON *products_item = cJSON_GetObjectItem(root, "products"); if (cJSON_IsArray(products_item)) { int size = cJSON_GetArraySize(products_item); for (int i = 0; i < size; i++) { cJSON *product = cJSON_GetArrayItem(products_item, i); if (cJSON_IsObject(product)) { cJSON *name_item = cJSON_GetObjectItem(product, "name"); if (name_item && cJSON_IsString(name_item)) { char *name = cJSON_GetStringValue(name_item); printf("Product name: %s\n", name); } } } } cJSON_Delete(root); } return 0; }
4.4.11 cJSON_IsObject
#include <stdio.h> #include "cJSON.h" int main() { const char *json_string = "{\"user\":{\"name\":\"John\", \"age\":30}}"; cJSON *root = cJSON_Parse(json_string); if (root && cJSON_IsObject(root)) { cJSON *user_item = cJSON_GetObjectItem(root, "user"); if (cJSON_IsObject(user_item)) { cJSON *name_item = cJSON_GetObjectItem(user_item, "name"); if (name_item && cJSON_IsString(name_item)) { char *name = cJSON_GetStringValue(name_item); printf("User name: %s\n", name); } } cJSON_Delete(root); } return 0; }
4.4.12 cJSON_IsRaw
#include <stdio.h> #include "cJSON.h" int main() { const char *json_string = "{\"raw_data\":\"<some_raw_content>\", \"name\":\"John\"}"; cJSON *root = cJSON_Parse(json_string); if (root && cJSON_IsObject(root)) { cJSON *raw_data_item = cJSON_GetObjectItem(root, "raw_data"); if (cJSON_IsRaw(raw_data_item)) { // 进行针对原始类型数据的特殊处理 //... } cJSON_Delete(root); } return 0; }
4.5
4.5.1 cJSON_CreateNull
#include "cJSON.h" int main() { cJSON *nullItem = cJSON_CreateNull(); // 这里可以将nullItem添加到一个更大的JSON结构中,例如一个对象或者数组 cJSON_Delete(nullItem); return 0; }
4.5.2 cJSON_CreateTrue
#include "cJSON.h" int main() { cJSON *trueItem = cJSON_CreateTrue(); // 可以将trueItem添加到一个JSON对象或者数组中 cJSON_Delete(trueItem); return 0; }
4.5.3 cJSON_CreateFalse
#include "cJSON.h" int main() { cJSON *falseItem = cJSON_CreateFalse(); // 将falseItem整合到一个JSON结构中 cJSON_Delete(falseItem); return 0; }
4.5.4 cJSON_CreateBool
#include "cJSON.h" int main() { cJSON_bool myBool = false; cJSON *boolItem = cJSON_CreateBool(myBool); // 对boolItem进行后续处理,如添加到其他JSON结构 cJSON_Delete(boolItem); return 0; }
4.5.5 cJSON_CreateNumber
#include "cJSON.h" int main() { double num = 3.14; cJSON *numberItem = cJSON_CreateNumber(num); // 将numberItem添加到一个JSON对象或者数组中 cJSON_Delete(numberItem); return 0; }
4.5.6 cJSON_CreateString
#include "cJSON.h" int main() { const char *str = "Hello, World!"; cJSON *stringItem = cJSON_CreateString(str); // 把stringItem添加到一个JSON结构中 cJSON_Delete(stringItem); return 0; }
4.5.7 cJSON_CreateRaw
#include "cJSON.h" int main() { const char *rawJson = "{\"subObject\":\"value\"}"; cJSON *rawItem = cJSON_CreateRaw(rawJson); // 将rawItem添加到一个JSON对象或者数组中 cJSON_Delete(rawItem); return 0; }
4.5.8 cJSON_CreateArray
#include "cJSON.h" int main() { cJSON *arrayItem = cJSON_CreateArray(); // 可以向arrayItem中添加其他的cJSON项,如数字、字符串等 cJSON_Delete(arrayItem); return 0; }
4.5.9 cJSON_CreateObject
#include "cJSON.h" int main() { cJSON *objectItem = cJSON_CreateObject(); // 可以向objectItem中添加键值对,如添加一个姓名属性 cJSON_AddItemToObject(objectItem, "name", cJSON_CreateString("John")); cJSON_Delete(objectItem); return 0; }
4.6
4.6.1 cJSON_CreateStringReference
#include "cJSON.h" int main() { const char *myString = "This is a test string"; cJSON *stringRefItem = cJSON_CreateStringReference(myString); // 使用stringRefItem构建更大的JSON结构或者进行其他操作 cJSON_Delete(stringRefItem); return 0; }
4.6.2 cJSON_CreateObjectReference
#include "cJSON.h" int main() { cJSON *childObject = cJSON_CreateObject(); cJSON_AddItemToObject(childObject, "name", cJSON_CreateString("Child")); cJSON *objectRef = cJSON_CreateObjectReference(childObject); // 使用objectRef构建更大的JSON结构或者进行其他操作 cJSON_Delete(objectRef); cJSON_Delete(childObject); return 0; }
4.6.3 cJSON_CreateArrayReference
#include "cJSON.h" int main() { cJSON *childItem = cJSON_CreateNumber(5); cJSON *arrayRef = cJSON_CreateArrayReference(childItem); // 使用arrayRef构建更大的JSON结构或者进行其他操作 cJSON_Delete(arrayRef); cJSON_Delete(childItem); return 0; }
4.6.4 cJSON_CreateIntArray
#include "cJSON.h" int main() { int numbers[] = {1, 2, 3}; int count = sizeof(numbers)/sizeof(numbers[0]); cJSON *intArray = cJSON_CreateIntArray(numbers, count); // 将intArray添加到一个更大的JSON结构中或者进行其他操作 cJSON_Delete(intArray); return 0; }
4.6.5 cJSON_CreateFloatArray
#include "cJSON.h" int main() { float numbers[] = {1.1f, 2.2f, 3.3f}; int count = sizeof(numbers)/sizeof(numbers[0]); cJSON *floatArray = cJSON_CreateFloatArray(numbers, count); // 对floatArray进行后续操作,如添加到其他JSON结构 cJSON_Delete(floatArray); return 0; }
4.6.6 cJSON_CreateDoubleArray
#include "cJSON.h" int main() { double numbers[] = {1.1, 2.2, 3.3}; int count = sizeof(numbers)/sizeof(numbers[0]); cJSON *doubleArray = cJSON_CreateDoubleArray(numbers, count); // 处理doubleArray,如将其整合到一个JSON对象中 cJSON_Delete(doubleArray); return 0; }
4.6.7 cJSON_CreateStringArray
#include "cJSON.h" int main() { const char *strings[] = {"apple", "banana", "cherry"}; int count = sizeof(strings)/sizeof(strings[0]); cJSON *stringArray = cJSON_CreateStringArray(strings, count); // 对stringArray进行操作,如添加到一个JSON对象中 cJSON_Delete(stringArray); return 0; }
4.7
4.7.1 cJSON_AddItemToArray
#include "cJSON.h" int main() { cJSON *array = cJSON_CreateArray(); cJSON *item = cJSON_CreateNumber(42); if (cJSON_AddItemToArray(array, item)) { char *jsonString = cJSON_Print(array); printf("%s\n", jsonString); free(jsonString); } cJSON_Delete(array); return 0; }
4.7.2 cJSON_AddItemToObject
#include "cJSON.h" int main() { cJSON *object = cJSON_CreateObject(); cJSON *nameItem = cJSON_CreateString("John"); if (cJSON_AddItemToObject(object, "name", nameItem)) { char *jsonString = cJSON_Print(object); printf("%s\n", jsonString); free(jsonString); } cJSON_Delete(object); return 0; }
4.7.3 cJSON_AddItemToObjectCS
#include "cJSON.h" int main() { cJSON *object = cJSON_CreateObject(); cJSON *valueItem = cJSON_CreateNumber(100); const char *key = "constant_key"; if (cJSON_AddItemToObjectCS(object, key, valueItem)) { char *jsonString = cJSON_Print(object); printf("%s\n", jsonString); free(jsonString); } cJSON_Delete(object); return 0; }
4.7.4 cJSON_AddItemReferenceToArray
#include "cJSON.h" int main() { cJSON *array = cJSON_CreateArray(); cJSON *sharedItem = cJSON_CreateString("Shared data"); if (cJSON_AddItemReferenceToArray(array, sharedItem)) { char *jsonString = cJSON_Print(array); printf("%s\n", jsonString); free(jsonString); } cJSON_Delete(array); return 0; }
4.7.5 cJSON_AddItemReferenceToObject
#include "cJSON.h" int main() { cJSON *object = cJSON_CreateObject(); cJSON *sharedObject = cJSON_CreateObject(); cJSON_AddItemToObject(sharedObject, "city", cJSON_CreateString("New York")); const char *key = "address"; if (cJSON_AddItemReferenceToObject(object, key, sharedObject)) { char *jsonString = cJSON_Print(object); printf("%s\n", jsonString); free(jsonString); } cJSON_Delete(object); return 0; }
4.8
4.8.1 cJSON_DetachItemViaPointer
#include "cJSON.h" int main() { cJSON *array = cJSON_CreateArray(); cJSON *item = cJSON_CreateNumber(42); cJSON_AddItemToArray(array, item); cJSON *detachedItem = cJSON_DetachItemViaPointer(array, item); if (detachedItem) { // 可以对detachedItem进行操作,例如修改它的值 cJSON *newArray = cJSON_CreateArray(); cJSON_AddItemToArray(newArray, detachedItem); char *jsonString = cJSON_Print(newArray); printf("%s\n", jsonString); free(jsonString); cJSON_Delete(newArray); } cJSON_Delete(array); return 0; }
4.8.2 cJSON_DetachItemFromArray
#include "cJSON.h" int main() { cJSON *array = cJSON_CreateArray(); cJSON *item1 = cJSON_CreateNumber(10); cJSON *item2 = cJSON_CreateNumber(20); cJSON_AddItemToArray(array, item1); cJSON_AddItemToArray(array, item2); cJSON *detachedItem = cJSON_DetachItemFromArray(array, 0); if (detachedItem) { char *jsonString = cJSON_Print(detachedItem); printf("%s\n", jsonString); free(jsonString); // 可以重新将detachedItem插入到其他地方或者修改后再插回原数组 } cJSON_Delete(array); return 0; }
4.8.3 cJSON_DeleteItemFromArray
#include "cJSON.h" int main() { cJSON *array = cJSON_CreateArray(); cJSON *item1 = cJSON_CreateNumber(10); cJSON *item2 = cJSON_CreateNumber(20); cJSON_AddItemToArray(array, item1); cJSON_AddItemToArray(array, item2); cJSON_DeleteItemFromArray(array, 0); char *jsonString = cJSON_Print(array); printf("%s\n", jsonString); free(jsonString); cJSON_Delete(array); return 0; }
4.8.4 cJSON_DetachItemFromObject
#include "cJSON.h" int main() { cJSON *object = cJSON_CreateObject(); cJSON *value = cJSON_CreateString("red"); cJSON_AddItemToObject(object, "color_preference", value); cJSON *detachedValue = cJSON_DetachItemFromObject(object, "color_preference"); if (detachedValue) { char *jsonString = cJSON_Print(detachedValue); printf("%s\n", jsonString); free(jsonString); // 可以对detachedValue进行操作,如修改后再插回原对象 } cJSON_Delete(object); return 0; }
4.8.5 cJSON_DetachItemFromObjectCaseSensitive
#include "cJSON.h" int main() { cJSON *object = cJSON_CreateObject(); cJSON *value = cJSON_CreateString("red"); cJSON_AddItemToObject(object, "Color_Preference", value); cJSON *detachedValue = cJSON_DetachItemFromObjectCaseSensitive(object, "Color_Preference"); if (detachedValue) { char *jsonString = cJSON_Print(detachedValue); printf("%s\n", jsonString); free(jsonString); // 可以对detachedValue进行操作,如修改后再插回原对象 } cJSON_Delete(object); return 0; }
4.8.6 cJSON_DeleteItemFromObject
#include "cJSON.h" int main() { cJSON *object = cJSON_CreateObject(); cJSON *value = cJSON_CreateString("abc123"); cJSON_AddItemToObject(object, "temporary_token", value); cJSON_DeleteItemFromObject(object, "temporary_token"); char *jsonString = cJSON_Print(object); printf("%s\n", jsonString); free(jsonString); cJSON_Delete(object); return 0; }
4.8.7 cJSON_DeleteItemFromObjectCaseSensitive
#include "cJSON.h" int main() { cJSON *object = cJSON_CreateObject(); cJSON *value = cJSON_CreateString("abc123"); cJSON_AddItemToObject(object, "Temporary_Token", value); cJSON_DeleteItemFromObjectCaseSensitive(object, "Temporary_Token"); char *jsonString = cJSON_Print(object); printf("%s\n", jsonString); free(jsonString); cJSON_Delete(object); return 0; }
4.9
4.9.1 cJSON_InsertItemInArray
#include <stdio.h> #include <cJSON/cJSON.h> int main() { // 创建一个空的cJSON数组 cJSON *array = cJSON_CreateArray(); if (!array) { perror("Failed to create array"); return 1; } // 创建一个新的cJSON项 cJSON *newItem = cJSON_CreateString("new element"); if (!newItem) { perror("Failed to create new item"); cJSON_Delete(array); return 1; } // 在数组的开头(位置0)插入新项 if (!cJSON_InsertItemInArray(array, 0, newItem)) { perror("Failed to insert item in array"); cJSON_Delete(array); cJSON_Delete(newItem); return 1; } char *jsonString = cJSON_Print(array); printf("The array after insertion: %s\n", jsonString); cJSON_Delete(array); cJSON_free(jsonString); return 0; }
4.9.2 cJSON_ReplaceItemViaPointer
#include <stdio.h> #include <cJSON/cJSON.h> int main() { // 创建一个父对象 cJSON *parent = cJSON_CreateObject(); if (!parent) { perror("Failed to create parent object"); return 1; } // 在父对象中创建一个子项 cJSON *originalItem = cJSON_CreateString("original value"); cJSON_AddItemToObject(parent, "key", originalItem); // 创建一个新的替换项 cJSON *replacementItem = cJSON_CreateString("replacement value"); // 通过指针替换子项 if (!cJSON_ReplaceItemViaPointer(parent, originalItem, replacementItem)) { perror("Failed to replace item via pointer"); cJSON_Delete(parent); cJSON_Delete(originalItem); cJSON_Delete(replacementItem); return 1; } char *jsonString = cJSON_Print(parent); printf("The object after replacement: %s\n", jsonString); cJSON_Delete(parent); cJSON_free(jsonString); return 0; }
4.9.3 cJSON_ReplaceItemInArray
#include <stdio.h> #include <cJSON/cJSON.h> int main() { // 创建一个cJSON数组并添加一些元素 cJSON *array = cJSON_CreateArray(); cJSON *item1 = cJSON_CreateString("element1"); cJSON *item2 = cJSON_CreateString("element2"); cJSON_AddItemToArray(array, item1); cJSON_AddItemToArray(array, item2); // 创建一个新的替换项 cJSON *newItem = cJSON_CreateString("new element2"); // 替换数组中的第二个元素(位置1) if (!cJSON_ReplaceItemInArray(array, 1, newItem)) { perror("Failed to replace item in array"); cJSON_Delete(array); cJSON_Delete(item1); cJSON_Delete(item2); cJSON_Delete(newItem); return 1; } char *jsonString = cJSON_Print(array); printf("The array after replacement: %s\n", jsonString); cJSON_Delete(array); cJSON_free(jsonString); return 0; }
4.9.4 cJSON_ReplaceItemInObject
#include <stdio.h> #include <cJSON/cJSON.h> int main() { // 创建一个cJSON对象 cJSON *object = cJSON_CreateObject(); if (!object) { perror("Failed to create object"); return 1; } // 在对象中添加一个键值对 cJSON *originalItem = cJSON_CreateString("original value"); cJSON_AddItemToObject(object, "key", originalItem); // 创建一个新的替换项 cJSON *newItem = cJSON_CreateString("replacement value"); // 替换对象中键为"key"的项 if (!cJSON_ReplaceItemInObject(object, "key", newItem)) { perror("Failed to replace item in object"); cJSON_Delete(object); cJSON_Delete(originalItem); cJSON_Delete(newItem); return 1; } char *jsonString = cJSON_Print(object); printf("The object after replacement: %s\n", jsonString); cJSON_Delete(object); cJSON_free(jsonString); return 0; }
4.9.5 cJSON_ReplaceItemInObjectCaseSensitive
#include <stdio.h> #include <cJSON/cJSON.h> int main() { // 创建一个cJSON对象 cJSON *object = cJSON_CreateObject(); if (!object) { perror("Failed to create object"); return 1; } // 在对象中添加一个键值对,键为"Key"(大写K) cJSON *originalItem = cJSON_CreateString("original value"); cJSON_AddItemToObject(object, "Key", originalItem); // 创建一个新的替换项 cJSON *newItem = cJSON_CreateString("replacement value"); // 尝试替换对象中键为"key"(小写k)的项,由于区分大小写,替换会失败 if (!cJSON_ReplaceItemInObjectCaseSensitive(object, "key", newItem)) { printf("Replacement failed as keys are case - sensitive\n"); } char *jsonString = cJSON_Print(object); printf("The object: %s\n", jsonString); cJSON_Delete(object); cJSON_free(jsonString); return 0; }
4.10
4.10.1 cJSON_Duplicate
#include <stdio.h> #include <cJSON.h> int main() { // 创建一个简单的cJSON对象 cJSON *root = cJSON_CreateObject(); cJSON_AddNumberToObject(root, "number", 10); cJSON *duplicated = cJSON_Duplicate(root, 1); if (duplicated) { char *duplicated_str = cJSON_Print(duplicated); printf("Duplicated JSON: %s\n", duplicated_str); cJSON_Delete(duplicated); free(duplicated_str); } cJSON_Delete(root); return 0; }
4.10.2 cJSON_Compare
#include <stdio.h> #include <cJSON.h> int main() { cJSON *obj1 = cJSON_CreateObject(); cJSON_AddStringToObject(obj1, "name", "John"); cJSON_AddNumberToObject(obj1, "age", 30); cJSON *obj2 = cJSON_CreateObject(); cJSON_AddStringToObject(obj2, "name", "John"); cJSON_AddNumberToObject(obj2, "age", 30); cJSON_bool equal = cJSON_Compare(obj1, obj2, 1); if (equal) { printf("The two cJSON objects are equal.\n"); } else { printf("The two cJSON objects are not equal.\n"); } cJSON_Delete(obj1); cJSON_Delete(obj2); return 0; }
4.10.3 cJSON_Minify
#include <stdio.h> #include <cJSON.h> int main() { char json_str[] = "{\n\t\"name\": \"John\",\n\t\"age\": 30\n}"; cJSON_Minify(json_str); printf("Minified JSON: %s\n", json_str); return 0; }
4.11
4.11.1 cJSON_AddNullToObject
#include <stdio.h> #include <cJSON.h> int main() { cJSON *root = cJSON_CreateObject(); cJSON *null_item = cJSON_AddNullToObject(root, "nullable_field"); if (null_item) { char *json_str = cJSON_Print(root); printf("JSON with null value: %s\n", json_str); cJSON_Delete(root); free(json_str); } return 0; }
4.11.2 cJSON_AddTrueToObject
#include <stdio.h> #include <cJSON.h> int main() { cJSON *root = cJSON_CreateObject(); cJSON *true_item = cJSON_AddTrueToObject(root, "is_logged_in"); if (true_item) { char *json_str = cJSON_Print(root); printf("JSON with true value: %s\n", json_str); cJSON_Delete(root); free(json_str); } return 0; }
4.11.3 cJSON_AddFalseToObject
#include <stdio.h> #include <cJSON.h> int main() { cJSON *root = cJSON_CreateObject(); cJSON *false_item = cJSON_AddFalseToObject(root, "is_feature_enabled"); if (false_item) { char *json_str = cJSON_Print(root); printf("JSON with false value: %s\n", json_str); cJSON_Delete(root); free(json_str); } return 0; }
4.11.4 cJSON_AddBoolToObject
#include <stdio.h> #include <cJSON.h> int main() { cJSON *root = cJSON_CreateObject(); cJSON_bool user_permission = 1; cJSON *bool_item = cJSON_AddBoolToObject(root, "can_edit", user_permission); if (bool_item) { char *json_str = cJSON_Print(root); printf("JSON with boolean value: %s\n", json_str); cJSON_Delete(root); free(json_str); } return 0; }
4.11.5 cJSON_AddNumberToObject
#include <stdio.h> #include <cJSON.h> int main() { cJSON *root = cJSON_CreateObject(); double price = 19.99; cJSON *number_item = cJSON_AddNumberToObject(root, "price", price); if (number_item) { char *json_str = cJSON_Print(root); printf("JSON with number value: %s\n", json_str); cJSON_Delete(root); free(json_str); } return 0; }
4.11.6 cJSON_AddStringToObject
#include <stdio.h> #include <cJSON.h> int main() { cJSON *root = cJSON_CreateObject(); char *name = "John"; cJSON *string_item = cJSON_AddStringToObject(root, "name", name); if (string_item) { char *json_str = cJSON_Print(root); printf("JSON with string value: %s\n", json_str); cJSON_Delete(root); free(json_str); } return 0; }
4.11.7 cJSON_AddRawToObject
#include <stdio.h> #include <cJSON.h> int main() { cJSON *root = cJSON_CreateObject(); char *raw = "{\"custom\":\"data\"}"; cJSON *raw_item = cJSON_AddRawToObject(root, "custom_data", raw); if (raw_item) { char *json_str = cJSON_Print(root); printf("JSON with raw value: %s\n", json_str); cJSON_Delete(root); free(json_str); } return 0; }
4.11.8 cJSON_AddObjectToObject
#include <stdio.h> #include <cJSON.h> int main() { cJSON *root = cJSON_CreateObject(); cJSON *sub_object = cJSON_AddObjectToObject(root, "department"); if (sub_object) { cJSON_AddStringToObject(sub_object, "name", "Sales"); char *json_str = cJSON_Print(root); printf("JSON with sub - object: %s\n", json_str); cJSON_Delete(root); free(json_str); } return 0; }
4.11.9 cJSON_AddArrayToObject
#include <stdio.h> #include <cJSON.h> int main() { cJSON *root = cJSON_CreateObject(); cJSON *array = cJSON_AddArrayToObject(root, "phone_numbers"); if (array) { cJSON_AddStringToObject(array, "", "123 - 456 - 7890"); char *json_str = cJSON_Print(root); printf("JSON with array: %s\n", json_str); cJSON_Delete(root); free(json_str); } return 0; }
4.12
4.12.1 cJSON_SetIntValue
#include <stdio.h> #include "cJSON.h" int main() { cJSON *user_info = cJSON_CreateObject(); int age = 25; cJSON_SetIntValue(user_info, age); // 可以通过以下方式验证设置是否成功 if (user_info!= NULL) { printf("Valueint: %d, Valuedouble: %lf\n", user_info->valueint, user_info->valuedouble); } cJSON_Delete(user_info); return 0; }
4.12.2 cJSON_SetNumberValue
#include <stdio.h> #include "cJSON.h" int main() { cJSON *trade_info = cJSON_CreateObject(); double price = 12.5; cJSON_SetNumberValue(trade_info, price); if (trade_info!= NULL) { // 假设可以通过某种方式获取设置后的数值进行验证 double retrieved_price; // 这里只是示例,实际获取方式可能不同 retrieved_price = trade_info->valuedouble; printf("Set price: %lf, Retrieved price: %lf\n", price, retrieved_price); } cJSON_Delete(trade_info); return 0; }
4.12.3 cJSON_SetValuestring
#include <stdio.h> #include "cJSON.h" int main() { cJSON *user_info = cJSON_CreateString("John"); cJSON_SetValuestring(user_info, "Mike"); if (user_info!= NULL) { printf("New valuestring: %s\n", user_info->valuestring); } cJSON_Delete(user_info); return 0; }
4.12.4 cJSON_SetBoolValue
#include <stdio.h> #include "cJSON.h" int main() { cJSON *feature_status = cJSON_CreateTrue(); cJSON_SetBoolValue(feature_status, false); if (feature_status!= NULL) { if (feature_status->type == cJSON_False) { printf("Feature is now disabled.\n"); } else { printf("Feature is enabled.\n"); } } cJSON_Delete(feature_status); return 0; }
4.12.5 cJSON_ArrayForEach
#include <stdio.h> #include "cJSON.h" int main() { cJSON *array = cJSON_CreateArray(); cJSON_AddItemToArray(array, cJSON_CreateNumber(1)); cJSON_AddItemToArray(array, cJSON_CreateNumber(2)); cJSON_AddItemToArray(array, cJSON_CreateNumber(3)); cJSON *element; cJSON_ArrayForEach(element, array) { if (element!= NULL) { printf("%lf ", element->valuedouble); } } printf("\n"); cJSON_Delete(array); return 0; }
4.13
4.13.1 cJSON_malloc、cJSON_free
#include <stdio.h> #include "cJSON.h" int main() { // 使用cJSON_malloc分配内存 cJSON *new_obj = (cJSON *)cJSON_malloc(sizeof(cJSON)); if (new_obj!= NULL) { // 进行一些初始化操作,这里省略 // 使用完毕后释放内存 cJSON_free(new_obj); } return 0; }