cJSON构建一个数组?

时间:2018-04-26 06:54:02

标签: cjson

嗯,我是cJSON的新手。 我想构建一个JSON格式的数据,如下所示:


    {
        "parmas": {
            "name":"testbox",
            "box1":[0,0],
            "box2":[2,2]
        }
    }

那么,我应该如何使用cJson.c& cJson.h源代码?

1 个答案:

答案 0 :(得分:0)

你可以这样做:

#include <cjson/cJSON.h>
#include <stdlib.h>
#include <stdio.h>

cJSON *create_point(double x, double y) {
    cJSON *point = cJSON_CreateArray();
    if (point == NULL) {
        goto fail;
    }

    cJSON *x_json = cJSON_CreateNumber(x);
    if (x_json == NULL) {
        goto fail;
    }
    cJSON_AddItemToArray(point, x_json);

    cJSON *y_json = cJSON_CreateNumber(y);
    if (y_json == NULL) {
        goto fail;
    }
    cJSON_AddItemToArray(point, y_json);

    return point;

fail:
    cJSON_Delete(point);
    return NULL;
}

cJSON *create_box() {
    cJSON *box = cJSON_CreateObject();
    if (box == NULL) {
        goto fail;
    }

    cJSON *params = cJSON_CreateObject();
    if (params == NULL) {
        goto fail;
    }
    cJSON_AddItemToObject(box, "params", params);

    cJSON *name = cJSON_CreateString("testbox");
    if (name == NULL) {
        goto fail;
    }
    cJSON_AddItemToObject(params, "name", name);

    cJSON *box1 = create_point(0, 0);
    if (box1 == NULL) {
        goto fail;
    }
    cJSON_AddItemToObject(params, "box1", box1);

    cJSON *box2 = create_point(2, 2);
    if (box2 == NULL) {
        goto fail;
    }
    cJSON_AddItemToObject(params, "box2", box2);

    return box;

fail:
    cJSON_Delete(box);
    return NULL;
}

int main() {
    int status = EXIT_SUCCESS;
    char *json = NULL;
    cJSON *box = create_box();
    if (box == NULL) {
        goto fail;
    }

    json = cJSON_Print(box);
    if (json == NULL) {
        goto fail;
    }

    printf("%s\n", json);

    goto cleanup;

fail:
    status = EXIT_FAILURE;
cleanup:
    cJSON_Delete(box);
    if (json != NULL) {
        free(json);
    }

    return status;
}

另请阅读我的documentation以了解其工作原理以及如何使用。