常用函数:
1、json结构体初始化
struct json_object*
2、向json结构体中添加key-value对
void json_object_object_add(
3、返回json结构体的字符串格式
const char* json_object_to_json_string(struct json_object *obj)
4、基本数据类型转换为json结构体
struct json_object*
struct json_object* json_object_new_int(int32_t i)
struct json_object* json_object_new_int64(int64_t i)
struct json_object* json_object_new_boolean(json_bool b)
struct json_object* json_object_new_double(double d)
5、json结构体打印
json_object_to_file( jsonfile , json_res );
printf("%s", json_object_to_json_string(json_res) );
6、 将一个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");
7、将json-object写回文件
int json_object_to_file(char *filename, struct json_object *obj)
举例:
json_object_from_file("test.json", pobj);
8、删除一个对象
void json_object_object_del(struct json_object* jso, const char *key);
9、增加一个对象
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));
10、释放对象
void json_object_put(struct json_object *jso);
使用举例
(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;
}