Json-c构建对象

来源:互联网 发布:路由器上网数据获得 编辑:程序博客网 时间:2024/06/12 16:40

Json-c构建对象

这篇文章着重介绍 Json-c 中对象创建的 API 及其示例。Json 的数据类型包括 null, boolean, int, double, string, object, array。在 json-c 中定义为枚举体类型:

enum json_type {    json_type_boolean,    json_type_double,    json_type_int,    json_type_object,    json_type_array,    json_type_string};

API

在 Json-c 中创建相应数据类型对象的 API 命名规范为:

 struct json_object* json_object_new_**( /*argument list*/);

举例如:

/*Create a json_type_object object*/struct json_object* json_object_new_object(void);/*Create a json_type_array object*/struct json_object* json_object_new_array(void)/*Create a json_type_boolean object*/struct json_object* json_object_new_boolean(json_bool b);/*Create a json_type_int object*/struct json_object* json_object_new_int(int32_t i);/*Create a json_type_double object*/struct json_object* json_object_new_double(double d);/*Create a json_type_string object*/struct json_object* json_object_new_string(const char *s);

相应地,获取对应类型的 json_object 的 API 名为:

return_type json_object_get_**(struct json_object *obj)

例如:

json_bool json_object_get_boolean(struct json_object *obj);int32_t json_object_get_int(struct json_object *obj);double json_object_get_double(struct json_object *obj);const char* json_object_get_string(struct json_object *obj);int json_object_get_string_len(struct json_object *obj);

这两种类型的 API,类似C++类的装换构造函数以及数据类型重载函数。
另外介绍两个经常用到的 API:

enum json_type json_object_get_type(struct json_object *obj);int json_object_is_type(struct json_object *obj, enum json_type type);

分别用于获取 json_object的数据类型,判断 json_object是否为指定的类型。

编程实例

#include <json-c/json.h>#include <stdio.h>int main(int argc, char* argv[]) {    json_object *jobj = json_object_new_object();    json_object *jstring = json_object_new_string("Hello world, this is JSON!");    json_object *jint = json_object_new_int(10);    json_object *jboolean = json_object_new_boolean(1);    json_object *jdouble = json_object_new_double(3.1415926);    json_object *jarray = json_object_new_array();    json_object *jstring1 = json_object_new_string("C");    json_object *jstring2 = json_object_new_string("C++");    json_object *jstring3 = json_object_new_string("Shell");    json_object *jstring4 = json_object_new_string("Python");    json_object_array_add(jarray, jstring1);    json_object_array_add(jarray, jstring2);    json_object_array_add(jarray, jstring3);    json_object_array_add(jarray, jstring4);    json_object_object_add(jobj, "Tifo", jstring);    json_object_object_add(jobj, "Techonical Blog", jboolean);    json_object_object_add(jobj, "Average Posts per day", jdouble);    json_object_object_add(jobj, "Number of Posts", jint);    json_object_object_add(jobj, "Catogories", jarray);    printf("The json object created: %s\n", json_object_to_json_string(jobj));    return 0;}

编译运行:

gcc -o proc demo5.c -ljson

运行效果:
这里写图片描述

参考链接

【json】json-c接口
json-c / libjson Tutorial with Examples

原创粉丝点击