这个工具类可能还不完善,也是将jsoncpp简单的封装,老鸟可以直接飘过了
用该类,首先要到网上下载jsoncpp(网上一搜就有了),解压后,将include/json文件夹放到系统有include的地方,比如我是在放在/usr/local/include/下
然后将lib_json复制到项目适当目录
好了,直接上代码:
JSONObject.h
/*
* JSONObject.h
*
* Created on: 2012-10-20
* Author: root
*/
#ifndef JSONOBJECT_H_
#define JSONOBJECT_H_
#include <json/json.h>
namespace util {
class JSONObject {
public:
JSONObject(std::string jsondata);
virtual ~JSONObject();
int getInt(std::string key);
double getDouble(std::string key);
bool getBool(std::string key);
std::string getString(std::string key);
private:
Json::Reader _reader;
Json::Value _value;
};
} /* namespace util */
#endif /* JSONOBJECT_H_ */
JSONObject.cpp
/*
* JSONObject.cpp
*
* Created on: 2012-10-20
* Author: root
*/
#include "JSONObject.h"
#include "../base/Exception.h"
namespace util {
using namespace base;
JSONObject::JSONObject(std::string jsondata) {
if (!_reader.parse(jsondata, _value)) {
throw Exception("jsondata format is error!");
}
}
JSONObject::~JSONObject() {
// TODO Auto-generated destructor stub
}
std::string JSONObject::getString(std::string key){
return _value[key].asString();
}
int JSONObject::getInt(std::string key){
if(_value[key].isInt() || _value[key].isDouble()){
return _value[key].asInt();
}
return 0;
}
double JSONObject::getDouble(std::string key){
if(_value[key].isInt() || _value[key].isDouble()){
return _value[key].asDouble();
}
return 0.0;
}
bool JSONObject::getBool(std::string key){
if(_value[key].isBool()){
return _value[key].asBool();
}
return false;
}
} /* namespace util */
该类只是做简单的处理,其实该类到今后会有很大作用,可以作各种序列化json数据用,不明白的同学可以去了解下gson(java的),可以将任意对象转化成json数据,反过来也一样可以,同进还支持各种过滤,真是方便