JSONCPP解析时比较麻烦,要判这判那的,于是直接简单封装了一个helper,如果要想面向对象可以直接改成类的静态成员。
jsoncpp_helper.h
#pragma once #if( defined(WIN32) || defined(WIN64) ) #include "jsoncpp/include/json/json.h" #else #include "jsoncpp/json/json.h" #endif #include <string> bool _TrimJsonValueString(Json::Value &Root,const char* pszNodeName,std::string& strOut); bool _TrimJsonValueInt(Json::Value &Root,int& nOut,bool bFromString = false); bool _TrimJsonValueUint(Json::Value &Root,unsigned int& nOut,bool bFromString = false); bool _TrimJsonValueInt64(Json::Value &Root,int64_t& nOut); bool _TrimJsonValueUint64(Json::Value &Root,uint64_t& nOut);jsoncpp_helper.cpp:
#include "jsoncpp_helper.h" bool _TrimJsonValueString(Json::Value &Root,std::string& strOut) { if (Root.isMember(pszNodeName) && !Root[pszNodeName].isNull() && Root[pszNodeName].isString()) { strOut = Root[pszNodeName].asString(); return true; } return false; } bool _TrimJsonValueInt(Json::Value &Root,bool bFromString) { if (bFromString) { std::string strTmp; if (!_TrimJsonValueString(Root,pszNodeName,strTmp)) return false; nOut = atoi(strTmp.c_str()); return true; } if (Root.isMember(pszNodeName) && !Root[pszNodeName].isNull() && Root[pszNodeName].isInt()) { nOut = Root[pszNodeName].asInt(); return true; } return false; } bool _TrimJsonValueUint(Json::Value &Root,strTmp)) return false; nOut = atoi(strTmp.c_str()); return true; } if (Root.isMember(pszNodeName) && !Root[pszNodeName].isNull() && Root[pszNodeName].isInt()) { nOut = Root[pszNodeName].asInt(); return true; } return false; } bool _TrimJsonValueInt64(Json::Value &Root,int64_t& nOut) { std::string strTmp; if (!_TrimJsonValueString(Root,strTmp)) return false; nOut = atoll(strTmp.c_str()); return true; } bool _TrimJsonValueUint64(Json::Value &Root,uint64_t& nOut) { std::string strTmp; if (!_TrimJsonValueString(Root,strTmp)) return false; nOut = atoll(strTmp.c_str()); return true; }