cJSON的使用教程(树外构建 out of tree build 概念)(组包概念)
Posted Dontla
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了cJSON的使用教程(树外构建 out of tree build 概念)(组包概念)相关的知识,希望对你有一定的参考价值。
Github:DaveGamble/cJSON
https://github.com/DaveGamble/cJSON
文章目录
- Github:DaveGamble/cJSON
- License
- Usage
License
omitted
Usage
Welcome to cJSON.
cJSON aims to be the dumbest possible parser that you can get your job done with. It’s a single file of C, and a single header file.
JSON is described best here: http://www.json.org/ It’s like XML, but fat-free. You use it to move data around, store things, or just generally represent your program’s state.
As a library, cJSON exists to take away as much legwork as it can, but not get in your way. As a point of pragmatism (i.e. ignoring the truth), I’m going to say that you can use it in one of two modes: Auto and Manual. Let’s have a quick run-through.
I lifted some JSON from this page: http://www.json.org/fatfree.html That page inspired me to write cJSON, which is a parser that tries to share the same philosophy as JSON itself. Simple, dumb, out of the way.
cJSON 旨在成为您可以完成工作的最愚蠢的解析器。 它是 C 的单个文件和单个头文件。
JSON 在这里描述得最好:http://www.json.org/ 它类似于 XML,但没有脂肪(意指不含多余的东西)。 你用它来移动数据,存储东西,或者只是一般地代表你的程序的状态。
作为一个库,cJSON 的存在是为了带走尽可能多的跑腿工作,但不会妨碍您。 作为实用主义的一点(即忽略事实),我会说您可以在以下两种模式之一中使用它:自动和手动。 让我们快速浏览一下。
我从这个页面中提取了一些 JSON:http://www.json.org/fatfree.html 该页面启发了我编写 cJSON,它是一个尝试与 JSON 本身共享相同理念的解析器。 简单,愚蠢,不碍事。
Building
There are several ways to incorporate cJSON into your project.
有几种方法可以将 cJSON 合并到您的项目中。
copying the source 复制源
Because the entire library is only one C file and one header file, you can just copy cJSON.h and cJSON.c to your projects source and start using it.
cJSON is written in ANSI C (C89) in order to support as many platforms and compilers as possible.
因为整个库只有一个 C 文件和一个头文件,您只需将 cJSON.h 和 cJSON.c 复制到您的项目源并开始使用它即可。
cJSON 是用 ANSI C (C89) 编写的,以便支持尽可能多的平台和编译器。
CMake
With CMake, cJSON supports a full blown build system. This way you get the most features. CMake with an equal or higher version than 2.8.5 is supported. With CMake it is recommended to do an out of tree build, meaning the compiled files are put in a directory separate from the source files. So in order to build cJSON with CMake on a Unix platform, make a build directory and run CMake inside it.
使用 CMake,cJSON 支持完整的构建系统。 这样您就可以获得最多的功能。 支持版本等于或高于 2.8.5 的 CMake。 使用 CMake 建议进行树外构建
,这意味着编译后的文件放在与源文件不同的目录中。 因此,为了在 Unix 平台上使用 CMake 构建 cJSON,创建一个构建目录并在其中运行 CMake。
mkdir build
cd build
cmake ..
This will create a Makefile and a bunch of other files. You can then compile it:
这将创建一个 Makefile 和一堆其他文件。 然后你可以编译它:
make
And install it with make install if you want. By default it installs the headers /usr/local/include/cjson and the libraries to /usr/local/lib. It also installs files for pkg-config to make it easier to detect and use an existing installation of CMake. And it installs CMake config files, that can be used by other CMake based projects to discover the library.
You can change the build process with a list of different options that you can pass to CMake. Turn them on with On and off with Off:
如果需要,可以使用 make install 安装它。 默认情况下,它将头文件 /usr/local/include/cjson 和库安装到 /usr/local/lib。 它还为 pkg-config 安装文件,以便更容易检测和使用现有的 CMake 安装。 它会安装 CMake 配置文件,其他基于 CMake 的项目可以使用这些文件来发现库。
您可以使用可以传递给 CMake 的不同选项列表来更改构建过程。 用 On 打开它们,用 Off 关闭它们:
- DENABLE_CJSON_TEST=On: Enable building the tests. (on by default)
- DENABLE_CJSON_UTILS=On: Enable building cJSON_Utils. (off by default)
- DENABLE_TARGET_EXPORT=On: Enable the export of CMake targets. Turn off if it makes problems. (on by default)
- DENABLE_CUSTOM_COMPILER_FLAGS=On: Enable custom compiler flags (currently for Clang, GCC and MSVC). Turn off if it makes problems. (on by default)
- DENABLE_VALGRIND=On: Run tests with valgrind. (off by default)
- DENABLE_SANITIZERS=On: Compile cJSON with AddressSanitizer and UndefinedBehaviorSanitizer enabled (if possible). (off by default)
- DENABLE_SAFE_STACK: Enable the SafeStack instrumentation pass. Currently only works with the Clang compiler. (off by default)
- DBUILD_SHARED_LIBS=On: Build the shared libraries. (on by default)
- DBUILD_SHARED_AND_STATIC_LIBS=On: Build both shared and static libraries. (off by default)
- DCMAKE_INSTALL_PREFIX=/usr: Set a prefix for the installation.
- DENABLE_LOCALES=On: Enable the usage of localeconv method. ( on by default )
- DCJSON_OVERRIDE_BUILD_SHARED_LIBS=On: Enable overriding the value of BUILD_SHARED_LIBS with -DCJSON_BUILD_SHARED_LIBS.
- DENABLE_CJSON_VERSION_SO: Enable cJSON so version. ( on by default )
If you are packaging cJSON for a distribution of Linux, you would probably take these steps for example:
mkdir build
cd build
cmake .. -DENABLE_CJSON_UTILS=On -DENABLE_CJSON_TEST=Off -DCMAKE_INSTALL_PREFIX=/usr
make
make DESTDIR=$pkgdir install
On Windows CMake is usually used to create a Visual Studio solution file by running it inside the Developer Command Prompt for Visual Studio, for exact steps follow the official documentation from CMake and Microsoft and use the online search engine of your choice. The descriptions of the the options above still generally apply, although not all of them work on Windows.
在 Windows 上,CMake 通常用于通过在 Visual Studio 的开发人员命令提示符中运行它来创建 Visual Studio 解决方案文件,具体步骤请遵循 CMake 和 Microsoft 的官方文档并使用您选择的在线搜索引擎。 上述选项的描述仍然普遍适用,尽管并非所有选项都适用于 Windows。
Makefile
NOTE: This Method is deprecated. Use CMake if at all possible. Makefile support is limited to fixing bugs.
If you don’t have CMake available, but still have GNU make. You can use the makefile to build cJSON:
Run this command in the directory with the source code and it will automatically compile static and shared libraries and a little test program (not the full test suite).
注意:此方法已弃用。 尽可能使用 CMake。 Makefile 支持仅限于修复错误。
如果您没有可用的 CMake,但仍有 GNU make。 您可以使用 makefile 构建 cJSON:
在包含源代码的目录中运行此命令,它将自动编译静态和共享库以及一个小测试程序(不是完整的测试套件)。
make all
If you want, you can install the compiled library to your system using make install. By default it will install the headers in /usr/local/include/cjson and the libraries in /usr/local/lib. But you can change this behavior by setting the PREFIX and DESTDIR variables: make PREFIX=/usr DESTDIR=temp install. And uninstall them with: make PREFIX=/usr DESTDIR=temp uninstall.
如果需要,可以使用 make install 将编译后的库安装到系统中。 默认情况下,它会将头文件安装在 /usr/local/include/cjson 中,并将库安装在 /usr/local/lib 中。 但是您可以通过设置 PREFIX 和 DESTDIR 变量来更改此行为:make PREFIX=/usr DESTDIR=temp install。 并使用以下命令卸载它们:make PREFIX=/usr DESTDIR=temp uninstall。
Vcpkg
You can download and install cJSON using the vcpkg dependency manager:
您可以使用 vcpkg 依赖管理器下载并安装 cJSON:
git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.sh
./vcpkg integrate install
vcpkg install cjson
The cJSON port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please create an issue or pull request on the vcpkg repository.
vcpkg 中的 cJSON 端口由 Microsoft 团队成员和社区贡献者保持最新。 如果版本过期,请在 vcpkg 存储库上创建问题或拉取请求。
Including cJSON
If you installed it via CMake or the Makefile, you can include cJSON like this:
如果你通过 CMake 或 Makefile 安装它,你可以像这样包含 cJSON:
#include <cjson/cJSON.h>
Data Structure
cJSON represents JSON data using the cJSON struct data type:
cJSON 使用 cJSON 结构体数据类型来表示 JSON 数据:
/* The cJSON structure: */
typedef struct cJSON
struct cJSON *next;
struct cJSON *prev;
struct cJSON *child;
int type;
char *valuestring;
/* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */
int valueint;
double valuedouble;
char *string;
cJSON;
An item of this type represents a JSON value. The type is stored in type as a bit-flag (this means that you cannot find out the type by just comparing the value of type).
To check the type of an item, use the corresponding cJSON_Is… function. It does a NULL check followed by a type check and returns a boolean value if the item is of this type.
The type can be one of the following:
此类型的项目表示 JSON 值。 类型作为位标志存储在类型中(这意味着您无法仅通过比较类型的值来找出类型)。
要检查项目的类型,请使用相应的 cJSON_Is… 函数。 它先进行 NULL 检查,然后进行类型检查,如果项目属于这种类型,则返回一个布尔值。
类型可以是以下之一:
- cJSON_Invalid (check with cJSON_IsInvalid): Represents an invalid item that doesn’t contain any value. You automatically have this type if you set the item to all zero bytes.
- cJSON_False (check with cJSON_IsFalse): Represents a false boolean value. You can also check for boolean values in general with cJSON_IsBool.
- cJSON_True (check with cJSON_IsTrue): Represents a true boolean value. You can also check for boolean values in general with cJSON_IsBool.
- cJSON_NULL (check with cJSON_IsNull): Represents a null value.
- cJSON_Number (check with cJSON_IsNumber): Represents a number value. The value is stored as a double in valuedouble and also in valueint. If the number is outside of the range of an integer, INT_MAX or INT_MIN are used for valueint.
- cJSON_String (check with cJSON_IsString): Represents a string value. It is stored in the form of a zero terminated string in valuestring.
- cJSON_Array (check with cJSON_IsArray): Represent an array value. This is implemented by pointing child to a linked list of cJSON items that represent the values in the array. The elements are linked together using next and prev, where the first element has prev.next == NULL and the last element next == NULL.
- cJSON_Object (check with cJSON_IsObject): Represents an object value. Objects are stored same way as an array, the only difference is that the items in the object store their keys in string.
- cJSON_Raw (check with cJSON_IsRaw): Represents any kind of JSON that is stored as a zero terminated array of characters in valuestring. This can be used, for example, to avoid printing the same static JSON over and over again to save performance. cJSON will never create this type when parsing. Also note that cJSON doesn’t check if it is valid JSON.
- cJSON_Invalid(使用 cJSON_IsInvalid 检查):表示不包含任何值的无效项。如果您将项目设置为全零字节,您将自动拥有此类型。
- cJSON_False(检查 cJSON_IsFalse):表示一个假布尔值。您还可以使用 cJSON_IsBool 通常检查布尔值。
- cJSON_True(检查 cJSON_IsTrue):表示一个真正的布尔值。您还可以使用 cJSON_IsBool 通常检查布尔值。
- cJSON_NULL(检查 cJSON_IsNull):表示空值。
- cJSON_Number(检查 cJSON_IsNumber):表示一个数字值。该值作为双精度值存储在 valuedouble 和 valueint 中。如果数字超出整数范围,则将 INT_MAX 或 INT_MIN 用于 valueint。
- cJSON_String(检查 cJSON_IsString):表示一个字符串值。它以 valuestring 中以零结尾的字符串的形式存储。
- cJSON_Array(检查 cJSON_IsArray):表示一个数组值。这是通过将 child 指向表示数组中的值的 cJSON 项的链接列表来实现的。元素使用 next 和 prev 链接在一起,其中第一个元素具有 prev.next == NULL,最后一个元素具有 next == NULL。
- cJSON_Object(检查 cJSON_IsObject):表示一个对象值。对象的存储方式与数组相同,唯一的区别是对象中的项目将它们的键存储在字符串中。
- cJSON_Raw(使用 cJSON_IsRaw 检查):表示任何类型的 JSON,存储为 valuestring 中以零结尾的字符数组。例如,这可以用来避免一遍又一遍地打印相同的静态 JSON 以节省性能。 cJSON 在解析时永远不会创建这种类型。另请注意,cJSON 不会检查它是否是有效的 JSON。
Additionally there are the following two flags:
此外,还有以下两个标志:
-
cJSON_IsReference: Specifies that the item that child points to and/or valuestring is not owned by this item, it is only a reference. So cJSON_Delete and other functions will only deallocate this item, not its child/valuestring.
-
cJSON_StringIsConst: This means that string points to a constant string. This means that cJSON_Delete and other functions will not try to deallocate string.
-
cJSON_IsReference:指定 child 指向的项目和/或 valuestring 不属于该项目,它只是一个引用。 所以 cJSON_Delete 和其他函数只会释放这个 item,而不是它的 child/valuestring。
-
cJSON_StringIsConst:这意味着字符串指向一个常量字符串。 这意味着 cJSON_Delete 和其他函数不会尝试释放字符串。
Working with the data structure 使用数据结构
For every value type there is a cJSON_Create… function that can be used to create an item of that type. All of these will allocate a cJSON struct that can later be deleted with cJSON_Delete. Note that you have to delete them at some point, otherwise you will get a memory leak.
Important: If you have added an item to an array or an object already, you mustn’t delete it with cJSON_Delete. Adding it to an array or object transfers its ownership so that when that array or object is deleted, it gets deleted as well. You also could use cJSON_SetValuestring to change a cJSON_String’s valuestring, and you needn’t to free the previous valuestring manually.
对于每个值类型,都有一个 cJSON_Create… 函数可用于创建该类型的项目。 所有这些都将分配一个 cJSON 结构,以后可以使用 cJSON_Delete 删除该结构。 请注意,您必须在某些时候删除它们,否则您会出现内存泄漏。
重要提示:如果您已经将项目添加到数组或对象中,则不得使用 cJSON_Delete 将其删除。 将其添加到数组或对象会转移其所有权,因此当删除该数组或对象时,它也会被删除。 您也可以使用 cJSON_SetValuestring 来更改 cJSON_String 的 valuestring,并且您不需要手动释放以前的 valuestring。
Basic types
-
null is created with cJSON_CreateNull
-
booleans are created with cJSON_CreateTrue, cJSON_CreateFalse or cJSON_CreateBool
-
numbers are created with cJSON_CreateNumber. This will set both valuedouble and valueint. If the number is outside of the range of an integer, INT_MAX or INT_MIN are used for valueint
-
strings are created with cJSON_CreateString (copies the string) or with cJSON_CreateStringReference (directly points to the string. This means that valuestring won’t be deleted by cJSON_Delete and you are responsible for its lifetime, useful for constants)
-
使用 cJSON_CreateNull 创建 null
-
使用 cJSON_CreateTrue、cJSON_CreateFalse 或 cJSON_CreateBool 创建布尔值
-
数字是用 cJSON_CreateNumber 创建的。 这将设置 valuedouble 和 valueint。 如果数字超出整数范围,则使用 INT_MAX 或 INT_MIN 作为 valueint
-
使用 cJSON_CreateString(复制字符串)或使用 cJSON_CreateStringReference(直接指向字符串。这意味着 valuestring 不会被 cJSON_Delete 删除,并且您负责它的生命周期,对常量有用)创建字符串
Arrays
You can create an empty array with cJSON_CreateArray. cJSON_CreateArrayReference can be used to create an array that doesn’t “own” its content, so its content doesn’t get deleted by cJSON_Delete.
To add items to an array, use cJSON_AddItemToArray to append items to the end. Using cJSON_AddItemReferenceToArray an element can be added as a reference to another item, array or string. This means that cJSON_Delete will not delete that items child or valuestring properties, so no double frees are occurring if they are already used elsewhere. To insert items in the middle, use cJSON_InsertItemInArray. It will insert an item at the given 0 based index and shift all the existing items to the right.
If you want to take an item out of an array at a given index and continue using it, use cJSON_DetachItemFromArray, it will return the detached item, so be sure to assign it to a pointer, otherwise you will have a memory leak.
Deleting items is done with cJSON_DeleteItemFromArray. It works like cJSON_DetachItemFromArray, but deletes the detached item via cJSON_Delete.
You can also replace an item in an array in place. Either with cJSON_ReplaceItemInArray using an index or with cJSON_ReplaceItemViaPointer given a pointer to an element. cJSON_ReplaceItemViaPointer will return 0 if it fails. What this does internally is to detach the old item, delete it and insert the new item in its place.
To get the size of an array, use cJSON_GetArraySize. Use cJSON_GetArrayItem to get an element at a given index.
Because an array is stored as a linked list, iterating it via index is inefficient (O(n²)), so you can iterate over an array using the cJSON_ArrayForEach macro in O(n) time complexity.
您可以使用 cJSON_CreateArray 创建一个空数组。 cJSON_CreateArrayReference 可用于创建不“拥有”其内容的数组,因此其内容不会被 cJSON_Delete 删除。
要将项目添加到数组,请使用 cJSON_AddItemToArray 将项目附加到末尾。使用 cJSON_AddItemReferenceToArray 可以将元素添加为对另一个项目、数组或字符串的引用。这意味着 cJSON_Delete 不会删除该项目的子属性或 valuestring 属性,因此如果它们已在其他地方使用,则不会发生双重释放。要在中间插入项目,请使用 cJSON_InsertItemInArray。它将在给定的基于 0 的索引处插入一个项目,并将所有现有项目向右移动。
如果要从给定索引处的数组中取出一个项目并继续使用它,请使用 cJSON_DetachItemFromArray,它将返回分离的项目,因此请务必将其分配给指针,否则会出现内存泄漏。
使用 cJSON_DeleteItemFromArray 删除项目。它的工作方式类似于 cJSON_DetachItemFromArray,但通过 cJSON_Delete 删除分离的项目。
您还可以就地替换数组中的项目。使用 cJSON_ReplaceItemInArray 使用索引或使用 cJSON_ReplaceItemViaPointer 给定指向元素的指针。如果失败,cJSON_ReplaceItemViaPointer 将返回 0。这在内部所做的是分离旧项目,将其删除并在其位置插入新项目。
要获取数组的大小,请使用 cJSON_GetArraySize。使用 cJSON_GetArrayItem 获取给定索引处的元素。
因为数组存储为链表,所以通过索引对其进行迭代是低效的 (O(n²)),因此您可以使用 cJSON_ArrayForEach 宏以 O(n) 的时间复杂度迭代数组。
Objects
You can create an empty object with cJSON_CreateObject. cJSON_CreateObjectReference can be used to create an object that doesn’t “own” its content, so its content doesn’t get deleted by cJSON_Delete.
To add items to an object, use cJSON_AddItemToObject. Use cJSON_AddItemToObjectCS to add an item to an object with a name that is a constant or reference (key of the item, string in the cJSON struct), so that it doesn’t get freed by cJSON_Delete. Using cJSON_AddItemReferenceToArray an element can be added as a reference to another object, array or string. This means that cJSON_Delete will not delete that items child or valuestring properties, so no double frees are occurring if they are already used elsewhere.
If you want to take an item out of an object, use cJSON_DetachItemFromObjectCaseSensitive, it will return the detached item, so be sure to assign it to a pointer, otherwise you will have a memory leak.
Deleting items is done with cJSON_DeleteItemFromObjectCaseSensitive. It works like cJSON_DetachItemFromObjectCaseSensitive followed by cJSON_Delete.
You can also replace an item in an object in place. Either with cJSON_ReplaceItemInObjectCaseSensitive using a key or with cJSON_ReplaceItemViaPointer given a pointer to an element. cJSON_ReplaceItemViaPointer will return 0 if it fails. What this does internally is to detach the old item, delete it and insert the new item in its place.
To get the size of an object, you can use cJSON_GetArraySize, this works because internally objects are stored as arrays.
If you want to access an item in an object, use cJSON_GetObjectItemCaseSensitive.
To iterate over an object, you can use the cJSON_ArrayForEach macro the same way as for arrays.
cJSON also provides convenient helper functions for quickly creating a new item and adding it to an object, like cJSON_AddNullToObject. They return a pointer to the new item or NULL if they failed.
您可以使用 cJSON_CreateObject 创建一个空对象。 cJSON_CreateObjectReference 可用于创建不“拥有”其内容的对象,因此其内容不会被 cJSON_Delete 删除。
要将项目添加到对象,请使用 cJSON_AddItemToObject。使用 cJSON_AddItemToObjectCS 将项目添加到名称为常量或引用的对象(项目的键,cJSON 结构中的字符串),这样它就不会被 cJSON_Delete 释放。使用 cJSON_AddItemReferenceToArray 可以将元素添加为对另一个对象、数组或字符串的引用。这意味着 cJSON_Delete 不会删除该项目的子属性或 valuestring 属性,因此如果它们已在其他地方使用,则不会发生双重释放。
如果你想从一个对象中取出一个item,使用cJSON_DetachItemFromObjectCaseSensitive,它会返回分离后的item,所以一定要给它赋值给一个指针,否则会出现内存泄漏。
使用 cJSON_DeleteItemFromObjectCaseSensitive 删除项目。它的工作方式类似于 cJSON_DetachItemFromObjectCaseSensitive 后跟 cJSON_Delete。
您还可以就地替换对象中的项目。使用 cJSON_ReplaceItemInObjectCaseSensitive 使用键或使用 cJSON_ReplaceItemViaPointer 给定指向元素的指针。如果失败,cJSON_ReplaceItemViaPointer 将返回 0。这在内部所做的是分离旧项目,将其删除并在其位置插入新项目。
要获取对象的大小,可以使用 cJSON_GetArraySize,这是因为内部对象存储为数组。
如果要访问对象中的项目,请使用 cJSON_GetObjectItemCaseSensitive。
要迭代对象,您可以使用 cJSON_ArrayForEach 宏,方法与数组相同。
cJSON 还提供了方便的帮助函数,用于快速创建新项目并将其添加到对象中,例如 cJSON_AddNullToObject。它们返回指向新项目的指针,如果失败则返回 NULL。
Parsing JSON 解析JSON串
Given some JSON in a zero terminated string, you can parse it with cJSON_Parse.
给定零终止字符串中的一些 JSON,您可以使用 cJSON_Parse 对其进行解析。
cJSON *json = cJSON_Parse(string);
Given some JSON in a string (whether zero terminated or not), you can parse it with cJSON_ParseWithLength.
给定字符串中的一些 JSON(无论是否以零结尾),您可以使用 cJSON_ParseWithLength 对其进行解析。
cJSON *json = cJSON_ParseWithLength(string, buffer_length);
It will parse the JSON and allocate a tree of cJSON items that represents it. Once it returns, you are fully responsible for deallocating it after use with cJSON_Delete.
The allocator used by cJSON_Parse is malloc and free by default but can be changed (globally) with cJSON_InitHooks.
If an error occurs a pointer to the position of the error in the input string can be accessed using cJSON_GetErrorPtr. Note though that this can produce race conditions in multithreading scenarios, in that case it is better to use cJSON_ParseWithOpts with return_parse_end. By default, characters in the input string that follow the parsed JSON will not be considered as an error.
If you want more options, use cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated). return_parse_end returns a pointer to the end of the JSON in the input string or the position that an error occurs at (thereby replacing cJSON_GetErrorPtr in a thread safe way). require_null_terminated, if set to 1 will make it an error if the input string contains data after the JSON.
If you want more options giving buffer length, use cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated).
它将解析 JSON 并分配代表它的 cJSON 项目树。一旦它返回,您将完全负责在与 cJSON_Delete 一起使用后释放它。
cJSON_Parse 使用的分配器是 malloc 并且默认情况下是释放的,但可以使用 cJSON_InitHooks (全局)更改。
如果发生错误,则可以使用 cJSON_GetErrorPtr 访问指向输入字符串中错误位置的指针。请注意,尽管这可能会在多线程场景中产生竞争条件,但在这种情况下,最好将 cJSON_ParseWithOpts 与 return_parse_end 一起使用。默认情况下,解析后的 JSON 后面的输入字符串中的字符不会被视为错误。
如果您需要更多选项,请使用 cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated)
。 return_parse_end 返回一个指针,指向输入字符串中 JSON 的结尾或发生错误的位置(从而以线程安全的方式替换 cJSON_GetErrorPtr)。 require_null_terminated,如果设置为 1,如果输入字符串包含 JSON 之后的数据,则会出错。
如果您想要更多选项来提供缓冲区长度,请使用 cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated)
。
Printing JSON 打印(遍历)JSON串
Given a tree of cJSON items, you can print them as a string using cJSON_Print.
char *string = cJSON_Print(json);
It will allocate a string and print a JSON representation of the tree into it. Once it returns, you are fully responsible for deallocating it after use with your allocator. (usually free, depends on what has been set with cJSON_InitHooks).
cJSON_Print will print with whitespace for formatting. If you want to print without formatting, use cJSON_PrintUnformatted.
If you have a rough idea of how big your resulting string will be, you can use cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt). fmt is a boolean to turn formatting with whitespace on and off. prebuffer specifies the first buffer size to use for printing. cJSON_Print currently uses 256 bytes for its first buffer size. Once printing runs out of space, a new buffer is allocated and the old gets copied over before printing is continued.
These dynamic buffer allocations can be completely avoided by using cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format). It takes a buffer to a pointer to print to and its length. If the length is reached, printing will fail and it returns 0. In case of success, 1 is returned. Note that you should provide 5 bytes more than is actually needed, because cJSON is not 100% accurate in estimating if the provided memory is enough.
它将分配一个字符串并将树的 JSON 表示打印到其中。一旦它返回,您将完全负责在使用分配器后释放它。 (通常是释放的,取决于 cJSON_InitHooks 的设置)。
cJSON_Print 将打印带有空格以进行格式化。如果要在不格式化的情况下打印,请使用 cJSON_PrintUnformatted。
如果您大致了解生成的字符串有多大,可以使用 cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt)
。 fmt 是一个布尔值,用于打开和关闭空格格式。 prebuffer 指定用于打印的第一个缓冲区大小。 cJSON_Print 当前使用 256 字节作为其第一个缓冲区大小。一旦打印空间用完,就会分配一个新的缓冲区,并在继续打印之前复制旧的缓冲区。
使用 cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format)
可以完全避免这些动态缓冲区分配。它需要一个缓冲区指向要打印到的指针及其长度。如果达到长度,则打印失败并返回 0。如果成功,则返回 1。请注意,您应该比实际需要多提供 5 个字节,因为 cJSON 在估计提供的内存是否足够时并不是 100% 准确的。
Example 示例
In this example we want to build and parse the following JSON:
在此示例中,我们要构建和解析以下 JSON:
"name": "Awesome 4K",
"resolutions": [
"width": 1280,
"height": 720
,
"width": 1920,
"height": 1080
,
"width": 3840,
"height": 2160
]
Printing 打印(序列化)发送端
Let’s build the above JSON and print it to a string:
让我们构建上面的 JSON 并将其打印为字符串:
//create a monitor with a list of supported resolutions 使用支持的分辨率列表创建监视器
//NOTE: Returns a heap allocated string, you are required to free it after use. 注意:返回一个堆分配的字符串,您需要在使用后释放它。
char *create_monitor(void)
const unsigned int resolution_numbers[3][2] =
1280, 720,
1920, 1080,
3840, 2160
;
char *string = NULL;
cJSON *name = NULL;
cJSON *resolutions = NULL;
cJSON *resolution = NULL;
cJSON *width = NULL;
cJSON *height = NULL;
size_t index = 0;
cJSON *monitor = cJSON_CreateObject();
if (monitor == NULL)
goto end;
name = cJSON_CreateString("Awesome 4K");
if (name == NULL)
goto end;
/* after creation was successful, immediately add it to the monitor,
* thereby transferring ownership of the pointer to it 创建成功后,立即将其添加到监视器中,从而将指针的所有权转移给它*/
cJSON_AddItemToObject(monitor, "name", name);
resolutions = cJSON_CreateArray();
if (resolutions == NULL)
goto end;
cJSON_AddItemToObject(monitor, "resolutions", resolutions);
for (index = 0; index < (sizeof(resolution_numbers) / (2 * sizeof(int))); ++index)
resolution = cJSON_CreateObject();
if (resolution == NULL)
goto end;
cJSON_AddItemToArray(resolutions, resolution);
width = cJSON_CreateNumber(resolution_numbers[index][0]);
if (width == NULL)
goto end;
cJSON_AddItemToObject(resolution, "width", width);
height = cJSON_CreateNumber(resolution_numbers[index][1]);
if (height == NULL)
goto end;
cJSON_AddItemToObject(resolution, "height", height);
string = cJSON_Print(monitor);
if (string == NULL)
fprintf(stderr, "Failed to print monitor.\\n");
end:
cJSON_Delete(monitor);
return string;
Alternatively we can use the cJSON_Add…ToObject helper functions to make our lives a little easier:
或者,我们可以使用 cJSON_Add…ToObject 辅助函数让我们的生活更轻松一些:(简化代码)
//NOTE: Returns a heap allocated string, you are required to free it after use. 注意:返回一个堆分配的字符串,您需要在使用后释放它。
char *create_monitor_with_helpers(void)
const unsigned int resolution_numbers[3][2] =
1280, 720,
1920, 1080,
3840, 2160
;
char *string = NULL;
cJSON *resolutions = NULL;
size_t index = 0;
cJSON *monitor = cJSON_CreateObject();
if (cJSON_AddStringToObject(monitor, "name", "Awesome 4K") == NULL)
goto end;
resolutions = cJSON_AddArrayToObject(monitor, "resolutions");
if (resolutions == NULL)
goto end;
for (index = 0; index < (sizeof(resolution_numbers) / (2 * sizeof(int))); ++index)
cJSON *resolution = cJSON_CreateObject();
if (cJSON_AddNumberToObject(resolution, "width", resolution_numbers[index][0]) == NULL)
goto end;
if (cJSON_AddNumberToObject(resolution, "height", resolution_numbers[index][1]) == NULL)
goto end;
cJSON_AddItemToArray(resolutions, resolution);
string = cJSON_Print(monitor);
if (string == NULL)
fprintf(stderr, "Failed to print monitor.\\n");
end:
cJSON_Delete(monitor);
return string;
vs上测试
#pragma warning(disable : 4996)
#include <stdio.h>
//#include <string.h>
#include "cJSON.h"
//create a monitor with a list of supported resolutions
//NOTE: Returns a heap allocated string, you are required to free it after use.
char* create_monitor(void)
const unsigned int resolution_numbers[3][2] =
1280, 720,
1920, 1080,
3840, 2160
;
char* string = NULL;
cJSON* name = NULL;
cJSON* resolutions = NULL;
cJSON* resolution = NULL;
cJSON* width = NULL;
cJSON* height = NULL;
size_t index = 0;
cJSON* monitor =以上是关于cJSON的使用教程(树外构建 out of tree build 概念)(组包概念)的主要内容,如果未能解决你的问题,请参考以下文章
机器学习 Out-of-Fold 折外预测详解 | 使用折外预测 OOF 评估模型的泛化性能和构建集成模型
使用 cx_Freeze 构建可执行文件时出错:IndexError: tuple index out of range
Silverlight实例教程 - Out of Browser开篇