[Linux/C/Json]Json安裝、試做

本篇筆記自己使用Linux環境下C的JSON

環境:Linux Ubuntu 14.0.1 (VM 9 workstations)
編譯器:Code Blocks

參考:json-c

測試項目:

  1. 如何取得/安裝
  2. 將結構轉jsonobj
  3. 列印出json字串
  4. 將json字串轉回jsonobj
  5. 將jsonobj轉回結構

  • 取得/安裝
執行:

$ sudo apt-get install libjson0 libjson0-dev
就這樣。官網中另外一行指令是用來debug的,但基本上敝人用不太到,所以沒裝
參考:官網
  • 專案事前準備
使用前記得先去設定lib
新增json

  • 剩下的詳見程式碼

完整程式碼:
#include <stdio.h>
#include <stdlib.h>
#include <json/json.h>
#include <string.h>

typedef struct _node
{
    int *fd;
    char *data;
} node;

node *node_create(int ,char *);

json_object *node_nodetojobj(node *nd)
{
    json_object * jobj = json_object_new_object();
    json_object_object_add(jobj,"fd",json_object_new_int(*(nd->fd)));
    json_object_object_add(jobj,"data",json_object_new_string(nd->data));
    return jobj;
}

node *node_jobjtonode(json_object * jobj)
{
    int fd = json_object_get_int(json_object_object_get(jobj,"fd"));
    char *data = json_object_get_string(json_object_object_get(jobj,"data"));
    return node_create(fd,data);
}

node *node_create(int fd,char *data)
{
    node *nd = (node *)malloc(sizeof(node));
    nd->fd = (int *)malloc(sizeof(int));
    *(nd->fd) = fd;
    nd->data= (char *)malloc(sizeof(char)*(strlen(data)+1));
    strcpy(nd->data,data);
    return nd;
}

void node_destory(node * nd)
{
    free(nd->fd);
    free(nd->data);
    free(nd);
}

int main()
{
    printf("\n\nBefore Parse\n------------------------------------------\n");
    node *nd = node_create(10,"Hello World\n");
    printf("nd:fd->%d,data->%s\n",*(nd->fd),nd->data);


    json_object *jobj = node_nodetojobj(nd);
    printf("\n\nAfter Parse\n------------------------------------------\n");
    char *JsonStr = json_object_to_json_string(jobj);
    printf("Json:%s\n",JsonStr);

    printf("\n\nFree nd,jobj\n------------------------------------------\n");
    node_destory(nd);
    free(jobj);

    jobj =  json_tokener_parse(JsonStr);
    nd = node_jobjtonode(jobj);
    printf("\n\nRecovery Parse\n------------------------------------------\n");
    printf("nd:fd->%d,data->%s\n",*(nd->fd),nd->data);
    return 0;
}


字串轉回jsonobj的部分已補上。(20150120)


以上。

沒有留言:

張貼留言