jsonc库使用

    xiaoxiao2021-12-14  17

    jsonc库使用

    作者:wangkangluo1 | 出处:博客园 | 2011/12/15 15:12:28 | 阅读58次

    原文地址:

     

    1: 下载json-c库源码文件 json-c-0.9.tar.gz

    2: 编译

    #apt-get install libjson0-dev libjson0 

    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    #include    #include    #include    #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

    原文:http://blog.csdn.net/toddor_c/article/details/7268020

    转载请注明原文地址: https://ju.6miu.com/read-964849.html

    最新回复(0)