使用 cJSON.h 创建 json 对象

create json object using cJSON.h

我正在尝试创建如下所示的 JSON 对象,但我无法在其中添加第二个项目,例如:

"CarType": "mercedes",
"carID": "merc123"

还有其他项目。

我想这样创建 JSON:

{
  cars: [
    {
      "CarType": "BMW",
      "carID": "bmw123"
    },
    {
      "CarType": "mercedes",
      "carID": "merc123"
    },
    {
      "CarType": "volvo",
      "carID": "vol123r"
    },
    {
      "CarType": "ford",
      "carID": "ford123"
    }
  ]
};

到目前为止我已经尝试过:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cJSON.h"

int main (void){
    char field_name[32], value[32], *out;
    cJSON *root,*car;

    root  = cJSON_CreateObject();
    car=  cJSON_CreateArray();

    cJSON_AddItemToObject(root, "CarType", cJSON_CreateString("BMW"));
    cJSON_AddItemToObject(root, "carID", cJSON_CreateString("bmw123"));
    cJSON_AddItemToArray(car, root);

    out = cJSON_Print(car);
    printf("%s\n",out);

    return 0;
}

我的输出是这样的(缩进与这里显示的完全一样):

[{
        "CarType":  "BMW",
        "carID":    "bmw123"
    }]

如果 json 字符串是固定的,您可以简单地使用 cJSON_Parse 函数,为此您需要使用 char* :

   const char* const json_string = 
"{ \
  \"cars\": [\
    {\
      \"CarType\": \"BMW\",\
      \"carID\": \"bmw123\"\
    },\
    {\
      \"CarType\": \"mercedes\",\
      \"carID\": \"merc123\"\
    },\
    {\
      \"CarType\": \"volvo\",\
      \"carID\": \"vol123r\"\
    },\
    {\
      \"CarType\": \"ford\",\
      \"carID\": \"ford123\"\
    }\
  ]\
}\
";

   cJSON * root = cJSON_Parse(json_string);  /* Play with root */

   //char *rendered = cJSON_Print(root);

根据要求更新,当输入数组不固定时

   const char* const carType[] ={"BMW", "Mercides", "Audi", "Farari"}; 
   const char* const carID[]  ={"bmw11", "m22", "a33", "f44"} ;

   size_t max_size = 4;
   cJSON *root,*car;

   root  = cJSON_CreateObject();
   car=  cJSON_CreateArray();

   for( size_t i = 0; i < max_size; ++i )
   {
      cJSON* item  = cJSON_CreateObject(); 
      cJSON_AddItemToObject(item, "CarType", cJSON_CreateString( carType[i] ));
      cJSON_AddItemToObject(item, "carID", cJSON_CreateString(carID[i]));

      cJSON_AddItemToArray(car, item);
   }


   cJSON_AddItemToObject( root, "cars", car );

以下代码将向您展示如何使用 cJSON_CreateObject()cJSON_CreateArray()cJSON_AddItemToObject()cJSON_AddItemToArray().

等 cJSON 函数

您必须将 cars 数组添加到 root 对象。之后,您必须将每个 car 创建为包含 CarTypecarID 项的对象。每个 car 对象都必须添加到 cars 数组。

它也很好地记录了示例 here at GitHub

编辑#1:

正如@JonnySchubert 指出的那样,有必要释放分配的资源。但在这种情况下释放根节点就足够了,因为将项目添加到数组或对象会转移它的所有权。换句话说:释放根节点将导致根下的所有节点也被释放。来自我上面链接的 GitHub 资源:

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.

编辑#2:

@lsalamon 提到您必须释放 cJSON_Print 的 return 值,请参阅 here on SO for example and the documentation

代码:

#include <stdio.h>
#include <stdlib.h>
#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(out);

   /* free all objects under root and root itself */
   cJSON_Delete(root)

   return 0;
}

输出:

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

此代码仅添加 2 辆汽车以显示用途。在您的实际应用程序中,您应该使用 C 数组和 for 循环来做到这一点。

我得到的另一个解决方案-

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cJSON.h"

int main (void){
    char field_name[32], value[32], *out;
    cJSON *root,*car;

    root  = cJSON_CreateObject();
    car=  cJSON_CreateArray();


    cJSON_AddItemToObject(root, "CarType", cJSON_CreateString("BMW"));
    cJSON_AddItemToObject(root, "carID", cJSON_CreateString("bmws123"));
    cJSON_AddItemToArray(car, root);

    root=NULL;
    root  = cJSON_CreateObject();

    cJSON_AddItemToObject(root, "CarType", cJSON_CreateString("Mercedies"));
    cJSON_AddItemToObject(root, "carID", cJSON_CreateString("mer123"));
    cJSON_AddItemToArray(car, root);



    out = cJSON_Print(car);
    printf("%s\n",out);


    return 0;
}