0

好吧,我是 cJSON 的新手。我想构建一个 JSON 格式的数据,像这样:

    {
        “帕尔马斯”:{
            “名称”:“测试箱”,
            "box1":[0,0],
            “盒子2”:[2,2]
        }
    }

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

4

2 回答 2

1

你可以这样做:

#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;
}

另外请阅读我的文档以了解它是如何工作的以及如何使用它。

于 2018-04-26T15:59:28.833 回答
0

我花了一点努力才真正学习并熟悉 cJSON,所以我可以让它完全按照我想要的方式工作,但它可以完成!相信我。需要注意的是内存泄漏。很容易创建错误的项目,或者忘记清理您可能创建的任何指针。如果您想查看更多使用 cJSON 的示例代码,请告诉我。我喜欢认为我已经做得很好了!:) 我不认为你会在好的 'ole C 中找到更好或更容易使用的库。就像@FSMaxB的答案一样,您几乎肯定会goto在您的 C 代码中使用它,所以只需接受它,并像您正在编写代码一样设计您的代码,以便其他人必须阅读和理解它。

于 2021-09-13T21:57:14.820 回答