您的位置:首页 > 运维架构 > Linux

Linux 下编译JsonCpp与使用

2011-08-19 15:38 495 查看
下载scons 在这里http://www.scons.org/

解压 tar -zxvf scons-2.0.1.tar.gz

设定环境变量

# export MYSCONS=解压的路径

# export SCONS_LIB_DIR=$MYSCONS/engine

开始编译jsoncpp

#cd jsoncpp-src-0.5.0

结果有一些错误 也可能是早期的版本

是如下的结果

# python $MYSCONS/script/scons.py platform=linux-gcc

经过测试 发现报错 查看路径下 没有scons.py文件

故改为scons,如下

# python $MYSCONS/script/scons platform=linux-gcc

通过 生成文件

libjson_linux-gcc-4.4.4_libmt.a

libjson_linux-gcc-4.4.4_libmt.so

使用时 需要讲头文件 即 include下的文件复制到工程下

使用示例

#include "json/json.h"

#include <string>

#include <iostream>

using namespace std;

int main()

{

string test ="{\"id\":1,\"name\":\"kurama\"}";

Json::Reader reader;

Json::Value value;

if (reader.parse(test,value))

{

if(!value["id"].isNull())

{

cout<<value["id"].asInt()<<endl;

cout<<value["name"].asString()<<endl;

}

编译 为了方便编译 我将静态库文件命名为libjson.a

g++ -o main main.cpp -L. -ljson

=======================================================================================================================

根据在线参考文档:http://jsoncpp.sourceforge.net/

编写了以下程序:

int main()

{

const std::string SYS_CFG_FILE("config.json");

if (!boost::filesystem::exists(SYS_CFG_FILE.c_str()))

{

cout << "error: file not exit" << endl;

return false;

}

std::ifstream is(SYS_CFG_FILE.c_str());

Json::Reader reader;

Json::Value root;

if (reader.parse(is, root))

{

std::string encoding = root.get("encoding", "UTF-8" ).asString();

if (!encoding.empty())

{

cout << encoding.c_str() << endl;

const Json::Value plugins = root["plug-ins"];

// Iterates over the sequence elements.

for ( unsigned int index = 0; index < plugins.size(); ++index )

{

cout << plugins[index].asString() << endl;

}

cout << root["indent"].get("length", 3).asInt() << endl;

cout << root["indent"].get("use_space", true).asBool() << endl;

}

else

{

// report to the user the failure and their locations in the document.

std::cout << "Failed to read data\n"

<< reader.getFormatedErrorMessages();

}

}

else

{

// report to the user the failure and their locations in the document.

std::cout << "Failed to parse configuration\n"

<< reader.getFormatedErrorMessages();

return -1;

}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: