1: 下载json-c库源码文件json-c-0.9.tar.gz
2: 编译
3: json-c常用函数(1): 将一个json文件转换成object对象: struct json_object* json_object_from_file(char *filename)举例: json_object *pobj = NULL;pobj = json_object_from_file("/home/boy/tmp/test/jsontest/test.json");
(2): 将json-object写回文件int json_object_to_file(char *filename, struct json_object *obj)举例:json_object_from_file("/home/boy/tmp/test/jsontest/test.json", pobj);
(3): 删除一个对象void json_object_object_del(struct json_object* jso, const char *key);
(4): 增加一个对象void json_object_object_add(struct json_object* jso, const char *key, struct json_object *val);举例:json_object_object_add(pobj, "Name", json_object_new_string("Andy"));json_object_object_add(pobj, "Age", json_object_new_int(200));
(5): 释放对象void json_object_put(struct json_object *jso);
4: 使用举例(1): 新建一个x.json文件{"item1": "I love JSON","foo": "You love Json", "item3": "We love JSON","Name": "Andy","Age": 28}(2): 程序
#include <stdlib.h>#include <stdio.h>#include <unistd.h>#include <string.h>#include "json.h"
void GetValByKey(json_object * jobj, const char *sname){ json_object *pval = NULL; enum json_type type; pval = json_object_object_get(jobj, sname); if(NULL!=pval){ type = json_object_get_type(pval); switch(type) { case json_type_string: PRintf("Key:%s value: %s/n", sname, json_object_get_string(pval)); break; case json_type_int: printf("Key:%s value: %d/n", sname, json_object_get_int(pval)); break; default: break; } }}
int main(void){ json_object *pobj = NULL;
//pobj = json_tokener_parse("{ /"abc/": 12, /"foo/": /"bar/", /"bool0/": false, /"bool1/": true, /"arr/": [ 1, 2, 3, null, 5 ] }");
//printf("new_obj.to_string()=%s/n", json_object_to_json_string(pobj));
//json_parse(pobj);
pobj = json_object_from_file("/home/boy/tmp/test/jsontest/test.json"); GetValByKey(pobj, "foo");
json_object_object_del(pobj, "foo"); json_object_object_add(pobj, "foo", json_object_new_string("fark")); json_object_object_add(pobj, "Age", json_object_new_int(200)); GetValByKey(pobj, "Age"); json_object_to_file("/home/boy/tmp/test/jsontest/new.json", pobj);
json_object_put(pobj); return 0;}
Makefile
all:server
server: gcc -std=c99 -msse2 -Wall -O3 -o main main.c -ljson -lcrypto -lm -lpthread
完
新闻热点
疑难解答