cJson使用案例

#include 
#include 
#include "cJSON.h"

int main()
 {
     char *out;
     cJSON *root, *cars, *car;

   /* create root node and array */
   root = cJSON_CreateObject();
   cars = cJSON_CreateArray();

   /* add cars array to root */
   cJSON_AddItemToObject(root, "cars", cars);

   /* add 1st car to cars array */
   cJSON_AddItemToArray(cars, car = cJSON_CreateObject());
   cJSON_AddItemToObject(car, "CarType", cJSON_CreateString("BMW"));
   cJSON_AddItemToObject(car, "carID", cJSON_CreateString("bmw123"));

   /* add 2nd car to cars array */
   cJSON_AddItemToArray(cars, car = cJSON_CreateObject());
   cJSON_AddItemToObject(car, "CarType", cJSON_CreateString("mercedes"));
   cJSON_AddItemToObject(car, "carID", cJSON_CreateString("mercedes123"));

   /* print everything */
   out = cJSON_Print(root);
   printf("%s\n", out);

   /* free all objects under root and root itself */
     cJSON_Delete(root)
       return 0;
}

Output

{
"cars": [{
        "CarType":  "BMW",
        "carID":    "bmw123"
    }, {
        "CarType":  "mercedes",
        "carID":    "mercedes123"
    }]
}

你可能感兴趣的:(cJson使用案例)