json-c常用API

什么是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));
    
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LEO-max

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值