如何使用cJSON构建数组及指定结构的JSON数据?
Hey there! Since you're new to cJSON, let's break this down step by step—we'll build your exact target JSON structure, and I'll highlight how array creation works along the way.
Step 1: Clarify the Target Structure
First, let's restate the JSON you want to build to make sure we're aligned:
{ "parmas": { "name":"testbox", "box1":[0,0], "box2":[2,2] } }
Note: You wrote "parmas" instead of "params"—I'll stick with your spelling in the code!
Step 2: Core cJSON Functions You'll Need
Before diving into code, let's cover the key functions we'll use (all from cJSON.h):
cJSON_CreateObject(): Makes a JSON object (the curly brace{}structures)cJSON_CreateArray(): Makes a JSON array (the square bracket[]structures)cJSON_CreateString()/cJSON_CreateNumber(): Creates primitive value nodes (strings, numbers)cJSON_AddItemToObject(): Adds a child node (object/array/value) to a parent object, linked to a keycJSON_AddItemToArray(): Adds a child node to a parent arraycJSON_Print(): Converts the cJSON tree to a human-readable stringcJSON_Delete(): Frees all memory used by the cJSON tree (critical to avoid leaks!)
Step 3: Build the JSON Tree Step-by-Step
1. Initialize the Root Object
Start with the outermost JSON object:
cJSON *root = cJSON_CreateObject(); if (root == NULL) { fprintf(stderr, "Failed to create root object\n"); return 1; }
Always check for NULL returns—memory allocation can fail!
2. Create the "parmas" Inner Object
Next, make the object that holds your fields:
cJSON *parmas_obj = cJSON_CreateObject(); if (parmas_obj == NULL) { fprintf(stderr, "Failed to create parmas object\n"); cJSON_Delete(root); // Clean up what we created so far return 1; }
3. Add the "name" String Field
Add the string value to parmas_obj—you can use a shortcut for this:
cJSON_AddStringToObject(parmas_obj, "name", "testbox");
(This is equivalent to cJSON_AddItemToObject(parmas_obj, "name", cJSON_CreateString("testbox")).)
4. Build the "box1" Array (Critical Part!)
This is where array creation happens—let's break it down:
// 1. Create an empty array cJSON *box1_array = cJSON_CreateArray(); if (box1_array == NULL) { fprintf(stderr, "Failed to create box1 array\n"); cJSON_Delete(parmas_obj); cJSON_Delete(root); return 1; } // 2. Add elements to the array cJSON_AddItemToArray(box1_array, cJSON_CreateNumber(0)); cJSON_AddItemToArray(box1_array, cJSON_CreateNumber(0)); // 3. Attach the array to the parmas object cJSON_AddItemToObject(parmas_obj, "box1", box1_array);
Repeat the same logic for box2:
cJSON *box2_array = cJSON_CreateArray(); if (box2_array == NULL) { // Cleanup logic here... } cJSON_AddItemToArray(box2_array, cJSON_CreateNumber(2)); cJSON_AddItemToArray(box2_array, cJSON_CreateNumber(2)); cJSON_AddItemToObject(parmas_obj, "box2", box2_array);
5. Attach "parmas" to the Root Object
Tie the inner object to the root:
cJSON_AddItemToObject(root, "parmas", parmas_obj);
6. Print and Clean Up
Finally, convert the tree to a string, print it, then free all memory:
char *json_str = cJSON_Print(root); if (json_str != NULL) { printf("Generated JSON:\n%s\n", json_str); free(json_str); // cJSON_Print allocates a string—free it separately! } // Free the entire cJSON tree (recursively cleans all child nodes) cJSON_Delete(root);
Full Complete Code Example
Here's the entire code put together with robust error handling:
#include <stdio.h> #include <stdlib.h> #include "cJSON.h" int main() { // Create root object cJSON *root = cJSON_CreateObject(); if (!root) { fprintf(stderr, "Error creating root object\n"); return 1; } // Create parmas object cJSON *parmas_obj = cJSON_CreateObject(); if (!parmas_obj) { fprintf(stderr, "Error creating parmas object\n"); cJSON_Delete(root); return 1; } // Add name field cJSON_AddStringToObject(parmas_obj, "name", "testbox"); // Build box1 array cJSON *box1_array = cJSON_CreateArray(); if (!box1_array) { fprintf(stderr, "Error creating box1 array\n"); cJSON_Delete(parmas_obj); cJSON_Delete(root); return 1; } cJSON_AddItemToArray(box1_array, cJSON_CreateNumber(0)); cJSON_AddItemToArray(box1_array, cJSON_CreateNumber(0)); cJSON_AddItemToObject(parmas_obj, "box1", box1_array); // Build box2 array cJSON *box2_array = cJSON_CreateArray(); if (!box2_array) { fprintf(stderr, "Error creating box2 array\n"); cJSON_Delete(parmas_obj); cJSON_Delete(root); return 1; } cJSON_AddItemToArray(box2_array, cJSON_CreateNumber(2)); cJSON_AddItemToArray(box2_array, cJSON_CreateNumber(2)); cJSON_AddItemToObject(parmas_obj, "box2", box2_array); // Attach parmas to root cJSON_AddItemToObject(root, "parmas", parmas_obj); // Print the JSON char *json_output = cJSON_Print(root); if (json_output) { printf("Resulting JSON:\n%s\n", json_output); free(json_output); } // Cleanup all allocated memory cJSON_Delete(root); return 0; }
Key Notes for cJSON Arrays
- Arrays can hold any cJSON node type: numbers, strings, objects, even other arrays! Just use
cJSON_AddItemToArray()to add them. - For large arrays, use a loop to add elements instead of writing each line manually (e.g., a for loop for an array of 10 numbers).
cJSON_Delete()recursively frees all child nodes, so deleting the root object cleans up everything—no need to delete each array/object individually.
内容的提问来源于stack exchange,提问作者Davonter




