当前位置: 首页 > 工具软件 > jsonapi > 使用案例 >

json-c常用API

陈嘉荣
2023-12-01

什么是Json

​ Json(JavaScript Object Notation,JS 对象简谱)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。

一些合法的Json实例:

键值对:(可以没有键只有值)

	 键      值 
      ↓       ↓
1. {"name": "Leo", "sex": "male"}
2. {"name": "Jack", "age": 18, "address": {"country": "china", "zip-code": "10000"}}
3. {"a": "1", "b": [1,2,3]}

Json-c API

json_object支持类型:

/* supported object types */

typedef enum json_type {
  /* If you change this, be sure to update json_type_to_name() too */
  json_type_null,
  json_type_boolean,
  json_type_double,
  json_type_int,
  json_type_object,
  json_type_array,
  json_type_string
} json_type;

  1. 将符合Json格式的字符串构造成为一个Json对象

    struct json_object * json_tokener_parse(const char *s);
    
  2. 将Json对象内容转换成Json格式的字符串

    const char *json_object_to_json_string(struct json_object *obj);
    
  3. 创建Json对象

    struct json_object *json_object_new_object();
    
  4. 往Json对象中添加键值对

    void json_object_object_add(struct json_object *obj, const char *key, struct json_object *value);
    
  5. 将C字符串转换为Json字符串格式的对象

    struct json_object* json_object_new_string(const char *s);
    
  6. 将整型数值转换为Json格式的对象

    struct json_object* json_object_new_int(int a);
    
  7. 获取Json对象的整型数值

    int32 json_object_get_int(struct json_object *obj);
    
  8. 获取Json对象的字符串值

    const char *json_object_get_string(struct json_object *obj);
    
  9. ​ 解析Json分为两步:

    ​ 第一步:根据键名,从Json对象中获取与对应数据的Json对象

    struct json_object *json;
    json_object_object_get_ex(obj, "name", &json);
    

    ​ 第二步:根据数据类型,将数据对应的Json对象转换为对应类型的数据

    json_type type = json_object_get_type(json);
    
    if(json_type_string == type){
        printf("name: %s\n". json_object_get_string(json));	//json对象转换成字符串类型
    }
    
    //类似的
    json_object_object_get_ex(obj, "age", &json);
    printf("age: %d\n", json_object_get_int(json));
    
    json_object_object_get_ex(obj, "sex", &json);
    printf("sex: %s\n", json_object_get_string(json));
    
 类似资料: