首先去下载json-c lib
下载地址:git clone http://25thandClement.com/~william/projects/libjson.git
下载完成后,src是json库文件, exampel中是两个实例文件。
但是讲解的不是很清楚。
如果我们要生成json格式并打印出出来,我们就可以使用如下代码:
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include "json.h"
int main (void)
{
int error;
struct json *J;
J = json_open(JSON_F_NONE, &error);
setlocale(LC_ALL, "");
json_push(J, ".Peoples");
//json_push(J, "thumbs[]");
json_setstring(J, "Andow", ".MEN[0].name");
json_setstring(J, "555 123 456", "MEN[0].phone");
json_setstring(J, "Andow1", ".MEN[1].name");
json_setstring(J, "555 123 456", "MEN[1].phone");
json_pop(J);
json_pop(J);
json_push(J, ".Peoples.thumb");
json_setstring(J, "Andow", "name");
json_setstring(J, "12344566", "phone");
json_setnumber(J, 123, "weigh");
json_pop(J);
json_setstring(J, "Beijing", ".Peoples.$", "Local");
//json_pop(J)
json_setstring(J, "Andow", ".thumbs[0]");
json_setstring(J, "androw1", ".thumbs[#]", json_count(J, ".thumbs"));
json_push(J, ".thumbs[#]", json_count(J, ".thumbs"));
json_setstring(J, "apple", ".");
json_pop(J);
json_setstring(J, "intel", ".thumbs[3]");
json_printfile(J, stdout, JSON_F_PRETTY);
return EXIT_SUCCESS;
}
运行结果如下:
{
"Peoples" : {
"Local" : "Beijing",
"MEN" : [
{
"name" : "Andow",
"phone" : "555 123 456"
},
{
"name" : "Andow1",
"phone" : "555 123 456"
}
],
"thumb" : {
"name" : "Andow",
"phone" : "12344566",
"weigh" : 123
}
},
"thumbs" : [
"Andow",
"androw1",
"apple",
"intel"
]
}