LINUX JSON C/C++安装及应用

C语言

安装Json

sudo apt-get install libjson0-dev 

应用

测试程序:
#include 
#include "json-c/json.h"
#include 

int main(int argc, char *argv[])
{
 printf("Hello World!\n");

    struct json_object *new_obj;
    new_obj =  json_tokener_parse("{ \"glossary\": { \"title\": \"example glossary\", \"pageCount\": 100} }");

    printf("new_obj.to_string()=%s\n",json_object_to_json_string(new_obj));

    new_obj = json_object_object_get(new_obj, "glossary");
    printf("new_obj.to_string()=%s\n",json_object_to_json_string(new_obj));

    new_obj = json_object_object_get(new_obj, "pageCount");

    int pageCount = json_object_get_int(new_obj);
    printf("page COunt=%d\n", pageCount);

    json_object_put(new_obj);

    //方法二
    //创建字符串型的json对象
    json_object *j_str = json_object_new_string("test string ");

    //创建一个数组对象
    json_object *j_array = json_object_new_array();

    //给元素添加到数组末尾
    json_object_array_add(j_array, json_object_new_string("China"));
    json_object_array_add(j_array, json_object_new_string("Autralia"));
    json_object_array_add(j_array, json_object_new_string("French"));

    //将上面创建的对象加入到json对象j_cfg中
    json_object *j_cfg = json_object_new_object();

    json_object_object_add(j_cfg, "str1", j_str);
    json_object_object_add(j_cfg, "array1", j_array);

    printf("j_cfg = %s\n", json_object_to_json_string(j_cfg));

    //修改Autralia为Korea,在实际中需要搜索Autralia的位置idx,这个改变传染到了j_cfg
    json_object_array_put_idx(j_array, 1, json_object_new_string("Korea"));

    //删除French
    json_object_array_put_idx(j_array, 2, NULL);
    json_object_a

    printf("j_cfg = %s\n", json_object_to_json_string(j_cfg));

    //将j_cfg保存在project的根目录下的文件jcfg.dat中,该文件没有则新建,有则销毁重新写入 释放
    json_object_to_file("json.dat", j_cfg);
    json_object_put(j_str);
    json_object_put(j_array);
    json_object_put(j_cfg);

    return 0;
}

编译:gcc -o test test.c -l json-c
执行:./test

C++语音

安装

sudo apt-get install libjsoncpp-dev

应用

测试程序:
#include 
#include 
#include "jsoncpp/json/json.h"
#include "jsoncpp/json/value.h"
#include "jsoncpp/json/writer.h"

using namespace std;

int main()
{
    cout << "Hello World!" << endl;

    Json::Value root;
    Json::FastWriter fast;

    root["ModuleType"] = Json::Value(1);
    root["MOduleCode"] = Json::Value("China");

    cout<

 

你可能感兴趣的:(Linux)