json使用

Api Reference

https://jansson.readthedocs.org/en/2.7/apiref.html

#include <jansson.h>

数据类型(Type)

json_type
The type of a JSON value. The following members are defined:

JSON_OBJECT
JSON_ARRAY
JSON_STRING
JSON_INTEGER
JSON_REAL
JSON_TRUE
JSON_FALSE
JSON_NULL

引用次数(Reference Count)

json_t *json_incref(json_t *json)
//Increment the reference count of json if it’s not NULL. Returns json.

void json_decref(json_t *json)
//Decrement the reference count of json. As soon as a call to json_decref() drops the reference count to zero, the value is destroyed and it can no longer be used.

Sample

Encoding(json -> char)

void on_chat(pc_client_t *client, const char *event, void *data) {
    json_t *json = (json_t * )data;
    const char *msg = json_dumps(json, 0);
    printf("%s %s\n", event, msg);
}

Decoding(char -> json)

void msg_send(const char *message, const char *rid, const char *from, const char *target) {
    const char *route = "chat.chatHandler.send";
    json_t *msg = json_object();
    json_t *str = json_string(message);
    json_object_set_new(msg, "content", str);
    json_object_set_new(msg, "rid", json_string(rid));
    json_object_set_new(msg, "from", json_string(from));
    json_object_set_new(msg, "target", json_string(target));

    pc_request_t *request = pc_request_new();
    pc_request(pomelo_client, request, route, msg, on_send_cb);
}

void on_send_cb(pc_request_t *req, int status, json_t *resp) {
    if(status == 0){
        printf("on_send_cb ok\n");
    } else {
        printf("on_send_cb bad\n");
    }
    json_t *msg = req->msg;
    json_decref(msg);
    pc_request_destroy(req);
}

json_loads

void MsgHandler::onChatCallback(pc_client_t *client, const char *event, void *data)
{
    json_t* json = (json_t* )data;
    const char* msg = json_dumps(json, 0);
    log("a: %s %s", event, msg);
    messageQueue->addObject(CCString::create(msg));
    CCString* str = CCString::create(msg);
    json_error_t error;
    json_t* js = json_loads(str->getCString(),0,&error);
    json_t* ms = json_object_get(js, "msg");
    msg = json_string_value(ms);
    log("b: %s %s", event, msg);
    return;
}

没整理好,先忙会儿再整理。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值