【发布时间】:2016-11-29 03:05:15
【问题描述】:
我最近通过 Cmake 安装了 David Gamble 的 cJSON 库,但出现以下错误:
在尝试像这样编译一个简单的 .c 代码时:
int main(int argc, const char * argv[]) {
/*{
"name": "Mars",
"mass": 639e21,
"moons": [
{
"name": "Phobos",
"size": 70
},
{
"name": "Deimos",
"size": 39
}
]
}*/
char *strJson = "{\"name\" : \"Mars\",\"mass\":639e21,\"moons\":[{\"name\":\"Phobos\",\"size\":70},{\"name\":\"Deimos\",\"size\":39}]}";
printf("Planet:\n");
// First, parse the whole thing
cJSON *root = cJSON_Parse(strJson);
// Let's get some values
char *name = cJSON_GetObjectItem(root, "name")->valuestring;
double mass = cJSON_GetObjectItem(root, "mass")->valuedouble;
printf("%s, %.2e kgs\n", name, mass); // Note the format! %.2e will print a number with scientific notation and 2 decimals
// Now let's iterate through the moons array
cJSON *moons = cJSON_GetObjectItem(root, "moons");
// Get the count
int moons_count = cJSON_GetArraySize(moons);
int i;
for (i = 0; i < moons_count; i++) {
printf("Moon:\n");
// Get the JSON element and then get the values as before
cJSON *moon = cJSON_GetArrayItem(moons, i);
char *name = cJSON_GetObjectItem(moon, "name")->valuestring;
int size = cJSON_GetObjectItem(moon, "size")->valueint;
printf("%s, %d kms\n", name, size);
}
// Finally remember to free the memory!
cJSON_Delete(root);
return 0;
}
如果我将 cJSON.c 的内容添加到我的代码中,它会解决问题,但会打印损坏的文件。
【问题讨论】:
标签: c gcc installation cjson