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

C语言

安装Json

sudo apt-get install libjson0-dev 

应用

测试程序:
#include <stdio.h>
#include "json-c/json.h"
#include <stdlib.h>

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 <iostream>
#include <string>
#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<<fast.write(root)<<endl;

    Json::Value sub;
    sub["version"] = Json::Value("1.0");
    sub["city"] = Json::Value(root);
    fast.write(sub);

    cout<<sub.toStyledString()<<endl;

    return 0;
}
编译:g++ -o test test.cc -l jsoncpp
运行:./test

 

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值