cJSONを使用することでC言語でJSONデータをサポート

2402 ワード

C言語自体がJSONデータをサポートしていないため、cJSONによりC言語がJSON形式のデータをサポートすることができる.
リンクを与えるのはここです
使用说明:以上のリンクのファイルをダウンロードして、中にcとhのファイルがあって、Cコードの中で头のファイルを含みます
#include <cJSON.h>

コンパイル時、cJSON.c一緒にコンパイルします.例えば、
gcc test.c cJSON.c -o out

コードの例を次に示します.
次のような形を作成します.
{
    "username": "changzhi",
    "password":"12345",
}
のJSON文字列
 
char *CreateAuthJSONData(char username[], char password[], char hostname[], char address[])
 {
    cJSON *root;    //    cJSON  
    char *data = NULL;

    //create a json
    root = cJSON_CreateObject();

    //add value into "root"
    cJSON_AddStringToObject(root, "username", username);
    cJSON_AddStringToObject(root, "password", password);
    cJSON_AddStringToObject(root, "hostname", hostname);
    cJSON_AddStringToObject(root, "address", address);

    data = cJSON_Print(root);// JSON   char     
    return data;
 }

JSON文字列の解析:
    recvJSON = cJSON_Parse(szBuffer);   //parse str to json

    size = cJSON_GetArraySize(recvJSON);//get json size
    
    for (i = 0; i < size; i++){
    
        arrayItem = cJSON_GetArrayItem(recvJSON, i);
        pr = cJSON_Print(arrayItem);

        printf("%s -> %s
", arrayItem->string, pr); }

なお、構造体cJSONでは、
/* The cJSON structure: */
typedef struct cJSON {
    struct cJSON *next,*prev;   /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
    struct cJSON *child;        /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */

    int type;                   /* The type of the item, as above. */

    char *valuestring;          /* The item's string, if type==cJSON_String */
    int valueint;               /* The item's number, if type==cJSON_Number */
    double valuedouble;         /* The item's number, if type==cJSON_Number */

    char *string;               /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
} cJSON;

char*stringに対応するのはjsonのkey部分です.
(詳細cJSONの内蔵関数はcJSON.hの関数の説明を参照)