zl程序教程

您现在的位置是:首页 >  系统

当前栏目

JsonCpp在Linux下的安装及简单使用

Linux安装 使用 简单 jsoncpp
2023-06-13 09:15:04 时间

jsoncpp安装过程记录及使用方法。

环境

  • Ubuntu 16.04
  • Python3
  • gcc/g++
  • jsoncpp-0.10.7.tar.gz(可以在github上该项目的release下载)

安装过程

可以通过将jsoncpp编译为静态库或动态库的方式使用,也可以通过引用其头文件的方式来使用。

在这里采用第二种方式,首先需要生成dist文件夹,里面有jsoncpp.cpp和两个头文件。

cd jsoncpp-0.10.7
python amalgamate.py #此步会生成dist文件夹

然后就可以自己写程序来使用jsoncpp了,要包含两个文件才行。

#include "json/json.h"
#include "jsoncpp.cpp"

具体的程序内容可以看下一节”使用方法”

通过以下命令来编译运行程序

g++ -o test test.cpp -I./jsoncpp-0.10.7/dist/ # -I根据dist所在的路径来写
./test

使用方法

通过程序来展现jsoncpp的使用方式

#include <iostream>
#include "json/json.h"
#include "jsoncpp.cpp"

using namespace std;

int main(){
    Json::Value json_temp;
    json_temp["name"]=Json::Value("haha");
    json_temp["age"]=Json::Value(23);

    Json::Value root;
    root["key1"]=json_temp;
    root["key2"].append(1234);
    root["key2"].append("abcd");
    root["key2"].append(1.234);

    //fast无格式输出
    Json::FastWriter fast_writer;
    cout<<"fastwriter: "<<endl;
    cout<<fast_writer.write(root)<<endl;

    //style格式化输出
    Json::StyledWriter style_writer;
    cout<<"stylewriter: "<<endl;
    cout<<style_writer.write(root)<<endl;

    //string输出
    string str=fast_writer.write(root);
    cout<<"string out:"<<endl<<str<<endl;

    //从字符串解析json
    Json::Reader reader;
    Json::Value res;
    if(!reader.parse(str,res)){
        cout<<"parse error"<<endl;
    }else{
        cout<<"parse successfully"<<endl;
        cout<<"key1 is :"<<endl<<res["key1"]<<endl;
    }

}

输出结果如下:

fastwriter:
{"key1":{"age":23,"name":"haha"},"key2":[1234,"abcd",1.234]}

stylewriter:
{
   "key1" : {
      "age" : 23,
      "name" : "haha"
   },
   "key2" : [ 1234, "abcd", 1.234 ]
}

string out:
{"key1":{"age":23,"name":"haha"},"key2":[1234,"abcd",1.234]}

parse successfully
key1 is :
{
	"age" : 23,
	"name" : "haha"
}

参考

欢迎与我分享你的看法。 转载请注明出处:http://taowusheng.cn/