首页 > 代码库 > json-cpp 库使用
json-cpp 库使用
Json-cpp
是一个使用c++开发的面向对象的json库。
核心数据结构
Reader是json-cpp数据的读取器,可以从文件流,字符串中读取json数据,使用下面的接口:
boolparse( const std::string &document,
Value &root,
bool collectComments = true);
boolparse( std::istream &is,
Value &root,
bool collectComments = true);
将所有的json解析到Value结果里面。
Value是json解析的结果,它通过key-value的方式用来代表整数、浮点数、UTF-8的字符串、或者是一个value数组等,这个与json的格式定义保持一致。它的类型可以通过type获取,type的定义如下:
/*
* brief Type of the value held by a Value object.
*/
enum ValueType
{
nullValue = http://www.mamicode.com/0, ///< ‘null‘ value
intValue, ///< signedinteger value
uintValue, ///< unsignedinteger value
realValue, ///< double value
stringValue, ///< UTF-8string value
booleanValue, ///< bool value
arrayValue, ///< array value(ordered list)
objectValue ///< objectvalue (collection of name/value pairs).
};
Value访问的常用接口:
const char *asCString() const;
std::string asString() const;
# ifdef JSON_USE_CPPTL
CppTL::ConstString asConstString() const;
# endif
Int asInt() const;
UInt asUInt() const;
Int64 asInt64() const;
UInt64 asUInt64() const;
LargestInt asLargestInt() const;
LargestUInt asLargestUInt() const;
float asFloat() const;
double asDouble() const;
bool asBool() const;
bool isNull() const;
bool isBool() const;
bool isInt() const;
bool isUInt() const;
bool isIntegral() const;
bool isDouble() const;
bool isNumeric() const;
bool isString() const;
bool isArray() const;
bool isObject() const;
/// Return true if the object has a member named key.
bool isMember( const char *key ) const;
/// Return true if the object has a member named key.
bool isMember( const std::string &key ) const;
# ifdef JSON_USE_CPPTL
/// Return true if the object has a member named key.
bool isMember( const CppTL::ConstString &key ) const;
# endif
/// \brief Return a list of the member names.
///
/// If null, return an empty list.
/// \pre type() is objectValue or nullValue
/// \post if type() was nullValue, it remains nullValue
Members getMemberNames() const;
使用方法
#include "json/json.h"
#include "iostream"
#include "string"
int main()
{
std::string strValue =http://www.mamicode.com/"[{/"name/":/"TOM/",/"id/":4},{/"name/":/"JACK/",/"id/":5}]";
Json::Reader reader;
Json::Value value;
if(reader.parse(strValue, value))
{
if (value.type() != Json::arrayValue) {
printf("Json type is not arrayValue %d\n", value.type());
return 0;
}
for(unsigned int i = 0;i < value.size(); i++)
{
if (value[i].type() != Json::objectValue) {
printf("Json type is not objectValue %d\n", value[i].type());
continue;
}
if(!value[i].isMember("name"))
continue;
std::string name = value[i]["name"].asString();
std::cout << "got name " << name <<std::endl;
if(!value[i].isMember("id"))
continue;
int id = value[i]["id"].asInt();
std::cout << "got id" << id << std::endl;
Json::Value::Members member = value[i].getMemberNames();
for(Json::Value::Members::iterator iter = member.begin(); iter !=member.end(); ++iter)
{
std::cout << "gotmember " << (*iter) << std::endl;
}
}
}
return 0;
}