檔案路徑json格式儲存
阿新 • • 發佈:2018-12-15
專案需要以json格式儲存指定檔案目錄結構,如需求如下所示:
簡要思路,遍歷指定目錄結構,儲存在list中,然後,取出每一條路徑結構,進行json格式化,
與已有json格式路徑物件相加。
生成json格式程式碼:
BOOL _makeValue(Json::Value & ret, const PFILEINFO pfileInfor) { BOOL blRet = FALSE; if (pfileInfor == nullptr) { _tprintf(_T("invlaid input value.")); return FALSE; } Json::Reader read; Json::Value root; Json::Value val; TStringList lstFileFolder; Split(lstFileFolder, pfileInfor->strFullPath.c_str(), _T("\\"), TRUE); for (auto rit = lstFileFolder.rbegin(); rit != lstFileFolder.rend(); rit++) { TString strfile = *rit; if (rit == lstFileFolder.rbegin()) { TString strExt = PathFindExtension(pfileInfor->strFullPath.c_str()); if (!strExt.empty()) { root["length:"] = pfileInfor->ullLength; root["size:"] = (double)pfileInfor->ullSize; val[converttostring(*rit)] = root; } else { root.clear(); val[converttostring(*rit)] = root; } ret = val; blRet = TRUE; } else { val.clear(); val[converttostring(*rit)] = ret; ret.clear(); ret = val; } } _tprintf(_T("make value:%s"), ret.toStyledString().c_str()); return blRet; }
json格式物件,累加處理程式碼:
Json::Value _add(const Json::Value & other, const Json::Value & another) { Json::Value ret = another; BOOL blFound = FALSE; auto lstother = other.getMemberNames(); auto lstanoter = another.getMemberNames(); for each (std::string varOther in lstother) { for each (std::string varAnoter in lstanoter) { if (strcmp(varOther.c_str(), varAnoter.c_str()) == 0) { _tprintf(_T("%s exist in two"), varOther.c_str()); blFound = TRUE; } } if (blFound) { ret[varOther] = _add(other[varOther], another[varOther]); } else { ret[varOther] = other[varOther]; } } return ret; }
ps:程式碼中,需要考慮異常情況。