背景
C/C++客戶端需要接收和發送JSON格式的數據到后端以實現通訊和數據交互。C++沒有現成的處理JSON格式數據的接口,直接引用第三方庫還是避免不了拆解拼接。考慮到此項目將會有大量JSON數據需要處理,避免不了重復性的拆分拼接。所以打算封裝一套C++結構體對象轉JSON數據、JSON數據直接裝C++結構體對象的接口,類似於數據傳輸中常見的序列化和反序列化,以方便后續處理數據,提高開發效率。
設計
目標:
- 通過簡單接口就能將C++結構體對象實例轉換為JSON字符串數據,或將一串JSON字符串數據加載賦值到一個C++結構體對象實例。理想接口:
Json2Object(inJsonString, outStructObject)
,或者Object2Json(inStructObject, outJsonString)
- 支持內置基本類型如bool,int,double的Json轉換,支持自定義結構體的Json轉換,支持上述類型作為元素數組的Json轉換,以及支持嵌套的結構體的Json轉換
效果:
先上單元測試代碼
TEST_CASE("解析結構體數組到JSON串", "[json]")
{
struct DemoChildrenObject
{
bool boolValue;
int intValue;
std::string strValue;
/*JSON相互轉換成員變量聲明(必需)*/
JSONCONVERT2OBJECT_MEMEBER_REGISTER(boolValue, intValue, strValue)
};
struct DemoObjct
{
bool boolValue;
int intValue;
std::string strValue;
/*嵌套的支持JSON轉換的結構體成員變量,數組形式*/
std::vector< DemoChildrenObject> children;
/*JSON相互轉換成員變量聲明(必需)*/
JSONCONVERT2OBJECT_MEMEBER_REGISTER(boolValue, intValue, strValue, children)
};
DemoObjct demoObj;
/*開始對demoObj對象的成員變量進行賦值*/
demoObj.boolValue = true;
demoObj.intValue = 321;
demoObj.strValue = "hello worLd";
DemoChildrenObject child1;
child1.boolValue = true;
child1.intValue = 1000;
child1.strValue = "hello worLd child1";
DemoChildrenObject child2;
child2.boolValue = true;
child2.intValue = 30005;
child2.strValue = "hello worLd child2";
demoObj.children.push_back(child1);
demoObj.children.push_back(child2);
/*結束對demoObj對象的成員變量的賦值*/
std::string jsonStr;
/*關鍵轉換函數*/
REQUIRE(Object2Json(jsonStr, demoObj));
std::cout << "returned json format: " << jsonStr << std::endl;
/*打印的內容如下:
returned json format: {
"boolValue" : true,
"children" : [
{
"boolValue" : true,
"intValue" : 1000,
"strValue" : "hello worLd child1"
},
{
"boolValue" : true,
"intValue" : 30005,
"strValue" : "hello worLd child2"
}
],
"intValue" : 321,
"strValue" : "hello worLd"
}
*/
DemoObjct demoObj2;
/*關鍵轉換函數*/
REQUIRE(Json2Object(demoObj2, jsonStr));
/*校驗轉換后的結構體變量中各成員變量的內容是否如預期*/
REQUIRE(demoObj2.boolValue == true);
REQUIRE(demoObj2.intValue == 321);
REQUIRE(demoObj2.strValue == "hello worLd");
REQUIRE(demoObj2.children.size() == 2);
REQUIRE(demoObj.children[0].boolValue == true);
REQUIRE(demoObj.children[0].intValue == 1000);
REQUIRE(demoObj.children[0].strValue == "hello worLd child1");
REQUIRE(demoObj.children[1].boolValue == true);
REQUIRE(demoObj.children[1].intValue == 30005);
REQUIRE(demoObj.children[1].strValue == "hello worLd child2");
}
實現
本次我們只關注怎么友好地在結構體與Json字符串之間進行轉換,而不深入關注JSon字符串具體如何與基本數據類型進行轉換。這個已經有不少的第三方庫幫我們解決這個問題,如cJSON、Jsoncpp、rapidjson,不必再重復造輪子。
此次我們選擇了JsonCPP作為底層的JSON解析支持,如果想替換成其他三方庫也比較簡單,修改對應嵌入的內容即可。
我們的目標是實現兩個接口:
-
Json2Object(inJsonString, outStructObject)
-
Object2Json(inStructObject, outJsonString)
結合JsonCPP自身定義的類型,我們進一步需要實現的是:
-
Json2Object(const Json::Value& jsonTypeValue, outStructObject)
-
Object2Json(inStructObject, const std::string& key, Json::Value& jsonTypeValue)
基本數據類型轉換
對於如bool、int、double、string等基本數據類型,該實現均較為簡單:
/*int 類型支持*/
static bool Json2Object(int& aimObj, const Json::Value& jsonTypeValue)
{
if (jsonTypeValue.isNull() || !jsonTypeValue.isInt()) {
return false;
} else {
aimObj = jsonTypeValue.asInt();
return true;
}
}
static bool Object2Json(Json::Value& jsonTypeValue, const std::string& key, const int& value)
{
jsonTypeValue[key] = value;
return true;
}
/*std::string 字符串類型支持*/
static bool Json2Object(std::string& aimObj, const Json::Value& jsonTypeValue)
{
if (jsonTypeValue.isNull() || !jsonTypeValue.isString()) {
return false;
} else {
aimObj = jsonTypeValue.asString();
return true;
}
}
static bool Object2Json(Json::Value& jsonTypeValue, const std::string& key, const std::string& value)
{
jsonTypeValue[key] = value;
return true;
}
自定義數據結構類型
對於自定義的結構體類型,我們要做的就是要保證其成員變量能夠與JSON節點一一對應,並能夠匹配進行數據填充。
/*Json字符串:
{
"boolValue" : true,
"intValue" : 1234,
"strValue" : "demo object!"
}*/
struct DemoObjct
{
bool boolValue;
int intValue;
std::string strValue;
};
如上面示例,在相互轉換過程中,"boolValue"能與DemoObjct對象中名為boolValue的成員變量對應,"strValue"與DemoObjct對象中名為strValue的成員變量對應。
正常情況下,對於這種場景,我們只能對DemoObjct結構體額外實現處理函數進行數據轉換,因不同的結構體聲明定義的成員變量都不一樣,所以針對每個結構體均需要單獨實現,工作繁瑣,不通用。
從這里下手,我們要做的就是“隱藏”針對類結構體實現的轉換函數,利用語言自身的特性(函數模板等)讓他們幫我們去做這些事情。
- 聲明轉換成員函數,在這個成員函數實現里,讓每個成員變量能從JSON原生數據中讀取或寫入值。
- 注冊成員變量,目的是讓轉換成員函數知道需要處理哪些成員變量,每個成員變量又對應JSON原生數據中的哪個節點字段,以便匹配讀寫。
- 在外部調用
Json2Object
和Object2Json
函數時,觸發調用該轉換成員函數,以便填充或輸出成員變量的內容。
把大象裝進冰箱里只需要三步,我們來看這三步怎么走。
成員變量處理
- 考慮到每個結構體的成員變量類型和數量不可控,並且需要將每個成員變量作為左值(
Json2Object
時),不能簡單采用數組枚舉方式處理,可以采用C++11的特性——可變參數模板,從里到外遍歷處理每個成員變量
template <typename T>
static bool JsonParse(const std::vector<std::string>& names, int index, const Json::Value& jsonTypeValue, T& arg)
{
const auto key = names[index];
if (!jsonTypeValue.isMember(key) || Json2Object(arg, jsonTypeValue[key])) {
return true;
} else {
return false;
}
}
template <typename T, typename... Args>
static bool JsonParse(const std::vector<std::string>& names, int index, const Json::Value& jsonTypeValue, T& arg, Args&... args)
{
if (!JsonParse(names, index, jsonTypeValue, arg)) {
return false;
} else {
return JsonParse(names, index + 1, jsonTypeValue, args...);
}
}
- 成員變量與JSON原生節點key字段有對應關系,初步先簡單考慮,將成員變量名稱先視為JSON中對應節點的key名稱。這個可以通過宏定義的特性實現,將聲明注冊的成員變量內容作為字符串拆分出key名稱列表。
#define JSONCONVERT2OBJECT_MEMEBER_REGISTER(...) \
bool ParseHelpImpl(const Json::Value& jsonTypeValue)
{
std::vector<std::string> names = Member2KeyParseWithStr(#__VA_ARGS__);
return JsonParse(names, 0, jsonTypeValue, __VA_ARGS__);
}
成員變量注冊
例如DemoObjct
這個類結構體,添加JSONCONVERT2OBJECT_MEMEBER_REGISTER
並帶上成員變量的注冊聲明:
struct DemoObjct
{
bool boolValue;
int intValue;
std::string strValue;
JSONCONVERT2OBJECT_MEMEBER_REGISTER(boolValue, intValue, strValue)
};
等同於:
struct DemoObjct
{
bool boolValue;
int intValue;
std::string strValue;
bool ParseHelpImpl(const Json::Value& jsonTypeValue,
std::vector<std::string> &names)
{
names = Member2KeyParseWithStr("boolValue, intValue, strValue");
//names 得到 ["boolValue","intValue", "strValue"]
//然后帶着這些key逐一從Json中取值賦值到成員變量中
return JsonParse(names, 0, jsonTypeValue, boolValue, intValue, strValue);
}
};
模板匹配防止編譯報錯
到目前為止,核心的功能已經實現。如果目標結構體類未添加JSON轉換的聲明注冊,外部在使用Json2Object
接口時會導致編譯報錯,提示找不到ParseHelpImpl
這個成員函數的聲明定義……,我們可以采用enable_if
來給未聲明注冊宏的結構體提供缺省函數。
template <typename TClass, typename enable_if<HasConverFunction<TClass>::has, int>::type = 0>
static inline bool Json2Object(TClass& aimObj, const Json::Value& jsonTypeValue)
{
std::vector<std::string> names = PreGetCustomMemberNameIfExists(aimObj);
return aimObj.JSONCONVERT2OBJECT_MEMEBER_REGISTER_RESERVERD_IMPLE(jsonTypeValue, names);
}
template <typename TClass, typename enable_if<!HasConverFunction<TClass>::has, int>::type = 0>
static inline bool Json2Object(TClass& aimObj, const Json::Value& jsonTypeValue)
{
return false;
}
成員變量匹配Key重命名
目前的實現均為將成員變量的名稱作為JSON串中的Key名稱,為靈活處理,再補充一個宏用於重新聲明結構體成員變量中對應到JSON串中的key,例如:
struct DemoObjct
{
bool boolValue;
int intValue;
std::string strValue;
JSONCONVERT2OBJECT_MEMEBER_REGISTER(boolValue, intValue, strValue)
/*重新聲明成員變量對應到JSON串的key,注意順序一致*/
JSONCONVERT2OBJECT_MEMEBER_RENAME_REGISTER("bValue", "iValue", "sValue")
};
DemoObjct demoObj;
/*boolValue <--> bValue; intValue <--> iValue; ...*/
REQUIRE(Json2Object(demoObj, std::string("{\"bValue\":true, \"iValue\":1234, \"sValue\":\"demo object!\"}")));
REQUIRE(demoObj.boolValue == true);
REQUIRE(demoObj.intValue == 1234);
REQUIRE(demoObj.strValue == "demo object!");
Object2Json實現
上面提到為大多為實現Json2Object
接口所提供的操作,從結構體對象轉成Json也是類似的操作,這里就不再闡述,詳細可參考源碼。
亮點
- 簡化C++對JSON數據的處理,屏蔽注意拆分處理JSON數據的操作;
- 提供簡易接口,從結構體到JSON串、JSON串轉結構體切換自如
源碼
#include "json/json.h"
#include <string>
#include <vector>
#include <initializer_list>
#define JSONCONVERT2OBJECT_MEMEBER_REGISTER(...) \
bool JSONCONVERT2OBJECT_MEMEBER_REGISTER_RESERVERD_IMPLE(const Json::Value& jsonTypeValue, std::vector<std::string> &names) \
{ \
if(names.size() <= 0) { \
names = Member2KeyParseWithStr(#__VA_ARGS__); \
} \
return JsonParse(names, 0, jsonTypeValue, __VA_ARGS__); \
} \
bool OBJECTCONVERT2JSON_MEMEBER_REGISTER_RESERVERD_IMPLE(Json::Value& jsonTypeValue, std::vector<std::string> &names) const \
{ \
if(names.size() <= 0) { \
names = Member2KeyParseWithStr(#__VA_ARGS__); \
} \
return ParseJson(names, 0, jsonTypeValue, __VA_ARGS__); \
} \
#define JSONCONVERT2OBJECT_MEMEBER_RENAME_REGISTER(...) \
std::vector<std::string> JSONCONVERT2OBJECT_MEMEBER_RENAME_REGISTER_RESERVERD_IMPLE() const \
{ \
return Member2KeyParseWithMultiParam({ __VA_ARGS__ }); \
}
namespace JSON
{
template <bool, class TYPE = void>
struct enable_if
{
};
template <class TYPE>
struct enable_if<true, TYPE>
{
typedef TYPE type;
};
} //JSON
template <typename T>
struct HasConverFunction
{
template <typename TT>
static char func(decltype(&TT::JSONCONVERT2OBJECT_MEMEBER_REGISTER_RESERVERD_IMPLE)); //@1
template <typename TT>
static int func(...); //@2
const static bool has = (sizeof(func<T>(NULL)) == sizeof(char));
template <typename TT>
static char func2(decltype(&TT::JSONCONVERT2OBJECT_MEMEBER_RENAME_REGISTER_RESERVERD_IMPLE)); //@1
template <typename TT>
static int func2(...); //@2
const static bool has2 = (sizeof(func2<T>(NULL)) == sizeof(char));
};
static std::vector<std::string> Member2KeyParseWithMultiParam(std::initializer_list<std::string> il)
{
std::vector<std::string> result;
for (auto it = il.begin(); it != il.end(); it++) {
result.push_back(*it);
}
return result;
}
inline static std::string NormalStringTrim(std::string const& str)
{
static char const* whitespaceChars = "\n\r\t ";
std::string::size_type start = str.find_first_not_of(whitespaceChars);
std::string::size_type end = str.find_last_not_of(whitespaceChars);
return start != std::string::npos ? str.substr(start, 1 + end - start) : std::string();
}
inline static std::vector<std::string> NormalStringSplit(std::string str, char splitElem)
{
std::vector<std::string> strs;
std::string::size_type pos1, pos2;
pos2 = str.find(splitElem);
pos1 = 0;
while (std::string::npos != pos2) {
strs.push_back(str.substr(pos1, pos2 - pos1));
pos1 = pos2 + 1;
pos2 = str.find(splitElem, pos1);
}
strs.push_back(str.substr(pos1));
return strs;
}
static std::vector<std::string> Member2KeyParseWithStr(const std::string& values)
{
std::vector<std::string> result;
auto enumValues = NormalStringSplit(values, ',');
result.reserve(enumValues.size());
for (auto const& enumValue : enumValues) {
result.push_back(NormalStringTrim(enumValue));
}
return result;
}
//////////////////////////////////////////////////////////////////////////////
static bool Json2Object(bool& aimObj, const Json::Value& jsonTypeValue)
{
if (jsonTypeValue.isNull() || !jsonTypeValue.isBool()) {
return false;
} else {
aimObj = jsonTypeValue.asBool();
return true;
}
}
static bool Object2Json(Json::Value& jsonTypeValue, const std::string& key, bool value)
{
jsonTypeValue[key] = value;
return true;
}
static bool Json2Object(int& aimObj, const Json::Value& jsonTypeValue)
{
if (jsonTypeValue.isNull() || !jsonTypeValue.isInt()) {
return false;
} else {
aimObj = jsonTypeValue.asInt();
return true;
}
}
static bool Object2Json(Json::Value& jsonTypeValue, const std::string& key, const int& value)
{
jsonTypeValue[key] = value;
return true;
}
static bool Json2Object(unsigned int& aimObj, const Json::Value& jsonTypeValue)
{
if (jsonTypeValue.isNull() || !jsonTypeValue.isUInt()) {
return false;
} else {
aimObj = jsonTypeValue.asUInt();
return true;
}
}
static bool Object2Json(Json::Value& jsonTypeValue, const std::string& key, const unsigned int& value)
{
jsonTypeValue[key] = value;
return true;
}
static bool Json2Object(double& aimObj, const Json::Value& jsonTypeValue)
{
if (jsonTypeValue.isNull() || !jsonTypeValue.isDouble()) {
return false;
} else {
aimObj = jsonTypeValue.asDouble();
return true;
}
}
static bool Object2Json(Json::Value& jsonTypeValue, const std::string& key, const double& value)
{
jsonTypeValue[key] = value;
return true;
}
static bool Json2Object(std::string& aimObj, const Json::Value& jsonTypeValue)
{
if (jsonTypeValue.isNull() || !jsonTypeValue.isString()) {
return false;
} else {
aimObj = jsonTypeValue.asString();
return true;
}
}
static bool Object2Json(Json::Value& jsonTypeValue, const std::string& key, const std::string& value)
{
jsonTypeValue[key] = value;
return true;
}
template <typename TClass, typename JSON::enable_if<HasConverFunction<TClass>::has2, int>::type = 0>
static inline std::vector<std::string> PreGetCustomMemberNameIfExists(const TClass& aimObj)
{
return aimObj.JSONCONVERT2OBJECT_MEMEBER_RENAME_REGISTER_RESERVERD_IMPLE();
}
template <typename TClass, typename JSON::enable_if<!HasConverFunction<TClass>::has2, int>::type = 0>
static inline std::vector<std::string> PreGetCustomMemberNameIfExists(const TClass& aimObj)
{
return std::vector<std::string>();
}
template <typename TClass, typename JSON::enable_if<HasConverFunction<TClass>::has, int>::type = 0>
static inline bool Json2Object(TClass& aimObj, const Json::Value& jsonTypeValue)
{
std::vector<std::string> names = PreGetCustomMemberNameIfExists(aimObj);
return aimObj.JSONCONVERT2OBJECT_MEMEBER_REGISTER_RESERVERD_IMPLE(jsonTypeValue, names);
}
template <typename TClass, typename JSON::enable_if<!HasConverFunction<TClass>::has, int>::type = 0>
static inline bool Json2Object(TClass& aimObj, const Json::Value& jsonTypeValue)
{
return false;
}
template <typename T>
static bool Json2Object(std::vector<T>& aimObj, const Json::Value& jsonTypeValue)
{
if (jsonTypeValue.isNull() || !jsonTypeValue.isArray()) {
return false;
} else {
aimObj.clear();
bool result(true);
for (int i = 0; i < jsonTypeValue.size(); ++i) {
T item;
if (!Json2Object(item, jsonTypeValue[i])) {
result = false;
}
aimObj.push_back(item);
}
return result;
}
}
template <typename T>
static bool JsonParse(const std::vector<std::string>& names, int index, const Json::Value& jsonTypeValue, T& arg)
{
const auto key = names[index];
if (!jsonTypeValue.isMember(key) || Json2Object(arg, jsonTypeValue[key])) {
return true;
} else {
return false;
}
}
template <typename T, typename... Args>
static bool JsonParse(const std::vector<std::string>& names, int index, const Json::Value& jsonTypeValue, T& arg, Args&... args)
{
if (!JsonParse(names, index, jsonTypeValue, arg)) {
return false;
} else {
return JsonParse(names, index + 1, jsonTypeValue, args...);
}
}
/** Provider interface*/
template<typename TClass>
bool Json2Object(TClass& aimObj, const std::string& jsonTypeStr)
{
Json::Reader reader;
Json::Value root;
if (!reader.parse(jsonTypeStr, root) || root.isNull()) {
return false;
}
return Json2Object(aimObj, root);
}
static bool GetJsonRootObject(Json::Value& root, const std::string& jsonTypeStr)
{
Json::Reader reader;
if (!reader.parse(jsonTypeStr, root)) {
return false;
}
return true;
}
////////////////////////////////////////////////////////////////////////
template <typename TClass, typename JSON::enable_if<HasConverFunction<TClass>::has, int>::type = 0>
static inline bool Object2Json(Json::Value& jsonTypeOutValue, const std::string& key, const TClass& objValue)
{
std::vector<std::string> names = PreGetCustomMemberNameIfExists(objValue);
if (key.empty()) {
return objValue.OBJECTCONVERT2JSON_MEMEBER_REGISTER_RESERVERD_IMPLE(jsonTypeOutValue, names);
} else {
Json::Value jsonTypeNewValue;
const bool result = objValue.OBJECTCONVERT2JSON_MEMEBER_REGISTER_RESERVERD_IMPLE(jsonTypeNewValue, names);
if (result) {
jsonTypeOutValue[key] = jsonTypeNewValue;
}
return result;
}
}
template <typename TClass, typename JSON::enable_if<!HasConverFunction<TClass>::has, int>::type = 0>
static inline bool Object2Json(Json::Value& jsonTypeOutValue, const std::string& key, const TClass& objValue)
{
return false;
}
template <typename T>
static bool Object2Json(Json::Value& jsonTypeOutValue, const std::string& key, const std::vector<T>& objValue)
{
bool result(true);
for (int i = 0; i < objValue.size(); ++i) {
Json::Value item;
if (!Object2Json(item, "", objValue[i])) {
result = false;
} else {
if (key.empty()) jsonTypeOutValue.append(item);
else jsonTypeOutValue[key].append(item);
}
}
return result;
}
template <typename T>
static bool ParseJson(const std::vector<std::string>& names, int index, Json::Value& jsonTypeValue, const T& arg)
{
if (names.size() > index) {
const std::string key = names[index];
return Object2Json(jsonTypeValue, key, arg);
} else {
return false;
}
}
template <typename T, typename... Args>
static bool ParseJson(const std::vector<std::string>& names, int index, Json::Value& jsonTypeValue, T& arg, Args&... args)
{
if (names.size() - (index + 0) != 1 + sizeof...(Args)) {
return false;
}
const std::string key = names[index];
Object2Json(jsonTypeValue, key, arg);
return ParseJson(names, index + 1, jsonTypeValue, args...);
}
/** Provider interface*/
template<typename T>
bool Object2Json(std::string& jsonTypeStr, const T& obj)
{
//std::function<Json::Value()>placehoder = [&]()->Json::Value { return Json::Value(); };
//auto func = [&](std::function<Json::Value()>f) { return f(); };
//Json::Value val = func(placehoder);
Json::StyledWriter writer;
Json::Value root;
const bool result = Object2Json(root, "", obj);
if (result) {
jsonTypeStr = writer.write(root);
}
return result;
}