概述
转自:https://blog.csdn.net/mengyafei43/article/details/38415665
常用函数:
1、json结构体初始化
struct json_object* json_object_new_object()
2、向json结构体中添加key-value对
void json_object_object_add( struct json_object* dest, const char *key, struct json_object *value )
3、返回json结构体的字符串格式
const char* json_object_to_json_string(struct json_object *obj)
4、基本数据类型转换为json结构体
struct json_object* json_object_new_string(const char *s)
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: %sn", sname, json_object_get_string(pval));
break;
case json_type_int:
printf("Key:%s value: %dn", 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()=%sn", 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;
}
from:
http://blog.sina.com.cn/s/blog_63041bb80101bq24.html
http://kuafu80.blog.163.com/blog/static/12264718020118182915988/
最后
以上就是正直火为你收集整理的json-c 0.12 使用介绍的全部内容,希望文章能够帮你解决json-c 0.12 使用介绍所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复