c++ Json.hpp 应用

上位参照

https://blog.csdn.net/baidu_33879812/article/details/107559843

json.hpp是一个非常强大的工具,只需要包含这个头文件,即可对json文件进行操作。
Git地址:https://github.com/nlohmann/json

Git上有简单的使用说明,简书这位作者已经将其汉化。
详见:https://www.jianshu.com/p/69e57f2af904?tdsourcetag=s_pctim_aiomsg

来源:鸿蒙代码


bool InnerBundleInfo::FromJson(const nlohmann::json &jsonObject)
{
    try {
        isSupportBackup_ = jsonObject.at(IS_SUPPORT_BACKUP).get<bool>();
        appType_ = jsonObject.at(APP_TYPE).get<Constants::AppType>();
        uid_ = jsonObject.at(UID).get<int>();
        gid_ = jsonObject.at(GID).get<int>();
        baseDataDir_ = jsonObject.at(BASE_DATA_DIR).get<std::string>();
        bundleStatus_ = jsonObject.at(BUNDLE_STATUS).get<BundleStatus>();
        baseBundleInfo_ = jsonObject.at(BASE_BUNDLE_INFO).get<BundleInfo>();
        baseApplicationInfo_ = jsonObject.at(BASE_APPLICATION_INFO).get<ApplicationInfo>();
        baseAbilityInfos_ = jsonObject.at(BASE_ABILITY_INFO).get<std::map<std::string, AbilityInfo>>();
        innerModuleInfos_ = jsonObject.at(INNER_MODULE_INFO).get<std::map<std::string, InnerModuleInfo>>();
        skillInfos_ = jsonObject.at(SKILL_INFOS).get<std::map<std::string, std::vector<Skill>>>();
        isKeepData_ = jsonObject.at(IS_KEEP_DATA).get<bool>();
        userId_ = jsonObject.at(USER_ID).get<int>();
        mainAbility_ = jsonObject.at(MAIN_ABILITY).get<std::string>();
        provisionId_ = jsonObject.at(PROVISION_ID).get<std::string>();
        appFeature_ = jsonObject.at(APP_FEATURE).get<std::string>();
        hasEntry_ = jsonObject.at(HAS_ENTRY).get<bool>();
    } catch (nlohmann::detail::parse_error &exception) {
        APP_LOGE("has a parse_error:%{public}s", exception.what());
        return false;
    } catch (nlohmann::detail::type_error &exception) {
        APP_LOGE("has a type_error:%{public}s.", exception.what());
        return false;
    } catch (nlohmann::detail::out_of_range &exception) {
        APP_LOGE("has an out_of_range exception:%{public}s.", exception.what());
        return false;
    }
    return true;
}

void InnerBundleInfo::ToJson(nlohmann::json &jsonObject) const
{
    jsonObject[IS_SUPPORT_BACKUP] = isSupportBackup_;
    jsonObject[APP_TYPE] = appType_;
    jsonObject[UID] = uid_;
    jsonObject[GID] = gid_;
    jsonObject[BASE_DATA_DIR] = baseDataDir_;
    jsonObject[BUNDLE_STATUS] = bundleStatus_;
    jsonObject[BASE_APPLICATION_INFO] = baseApplicationInfo_;
    jsonObject[BASE_BUNDLE_INFO] = baseBundleInfo_;
    jsonObject[BASE_ABILITY_INFO] = baseAbilityInfos_;
    jsonObject[INNER_MODULE_INFO] = innerModuleInfos_;
    jsonObject[SKILL_INFOS] = skillInfos_;
    jsonObject[IS_KEEP_DATA] = isKeepData_;
    jsonObject[USER_ID] = userId_;
    jsonObject[MAIN_ABILITY] = mainAbility_;
    jsonObject[PROVISION_ID] = provisionId_;
    jsonObject[APP_FEATURE] = appFeature_;
    jsonObject[HAS_ENTRY] = hasEntry_;
}

bool BundleDataStorage::LoadAllData(std::map<std::string, std::map<std::string, InnerBundleInfo>> &infos) const
{
    bool ret = false;
    APP_LOGI("load all installed bundle data to map");

    std::fstream i(Constants::BUNDLE_DATA_BASE_FILE);
    nlohmann::json jParse;
    if (!i.is_open()) {
        APP_LOGE("failed to open bundle database file");
        // if file not exist, should create file here
        std::ofstream o(Constants::BUNDLE_DATA_BASE_FILE);
        o.close();
        return false;
    }
    APP_LOGI("open bundle database file success");
    i.seekg(0, std::ios::end);
    int len = static_cast<int>(i.tellg());
    if (len > 0) {
        i.seekg(0, std::ios::beg);
        i >> jParse;
        for (auto &app : jParse.items()) {
            std::map<std::string, InnerBundleInfo> deviceMap;
            for (auto &device : app.value().items()) {
                InnerBundleInfo innerBundleInfo;
                ret = innerBundleInfo.FromJson(device.value());
                deviceMap.emplace(device.key(), innerBundleInfo);
            }
            auto pair = infos.emplace(app.key(), deviceMap);
            ret = pair.second;
        }
    }
    i.close();
    return ret;
}

bool BundleDataStorage::SaveStorageBundleInfo(const std::string &deviceId, const InnerBundleInfo &innerBundleInfo) const
{
    APP_LOGI("save bundle data");
    bool ret = true;
    std::string appName = innerBundleInfo.GetApplicationName();
    std::fstream f(Constants::BUNDLE_DATA_BASE_FILE);
    bool isExist = f.good();

    if (isExist) {
        nlohmann::json innerInfo;
        innerBundleInfo.ToJson(innerInfo);
        f.seekg(0, std::ios::end);
        int len = static_cast<int>(f.tellg());
        if (len == 0) {
            nlohmann::json appRoot;
            nlohmann::json app;
            app[deviceId] = innerInfo;
            appRoot[appName] = app;
            f << std::setw(Constants::DUMP_INDENT) << appRoot << std::endl;
        } else {
            f.seekg(0, std::ios::beg);
            nlohmann::json jsonFile;
            f >> jsonFile;
            if (jsonFile.find(appName) != jsonFile.end()) {
                if (jsonFile[appName].find(deviceId) != jsonFile[appName].end()) {
                    // appName and device id is exist
                    APP_LOGE("appName = %{public}s is exist", appName.c_str());
                    ret = false;
                } else {
                    jsonFile[appName][deviceId] = innerInfo;
                    f.seekp(0, std::ios::beg);
                    f << std::setw(Constants::DUMP_INDENT) << jsonFile << std::endl;
                }
            } else {
                nlohmann::json app;
                app[deviceId] = innerInfo;
                jsonFile[appName] = app;
                f.seekp(0, std::ios::beg);
                f << std::setw(Constants::DUMP_INDENT) << jsonFile << std::endl;
            }
        }
    } else {
        APP_LOGI("bundle database file not exist");
        ret = false;
    }
    f.close();
    return ret;
}

bool BundleDataStorage::ModifyStorageBundleInfo(
    const std::string &deviceId, const InnerBundleInfo &innerBundleInfo) const
{
    return true;
}

bool BundleDataStorage::DeleteStorageBundleInfo(
    const std::string &deviceId, const InnerBundleInfo &innerBundleInfo) const
{
    APP_LOGI("delete bundle data");
    bool ret = false;
    bool isEmpty = false;
    std::string appName = innerBundleInfo.GetApplicationName();
    std::ifstream i(Constants::BUNDLE_DATA_BASE_FILE);
    nlohmann::json jParse;
    if (!i.is_open()) {
        APP_LOGE("failed to open bundle database file");
        return false;
    } else {
        i.seekg(0, std::ios::end);
        int len = static_cast<int>(i.tellg());
        if (len != 0) {
            i.seekg(0, std::ios::beg);
            i >> jParse;
            if (jParse.find(appName) != jParse.end()) {
                auto it = jParse[appName].find(deviceId);
                if (it != jParse[appName].end()) {
                    jParse[appName].erase(it);
                    if (jParse[appName].size() == 0) {
                        jParse.erase(appName);
                        if (jParse.size() == 0) {
                            isEmpty = true;
                        }
                    }
                    ret = true;
                }
            } else {
                APP_LOGE("not find appName = %{public}s", appName.c_str());
            }
        } else {
            APP_LOGE("file is empty appName = %{private}s", appName.c_str());
        }
    }
    i.close();

    std::ofstream o(Constants::BUNDLE_DATA_BASE_FILE);
    if (!o.is_open()) {
        APP_LOGE("failed to open bundle database file");
        ret = false;
    } else {
        if (!isEmpty) {
            o << std::setw(Constants::DUMP_INDENT) << jParse;
        }
    }
    o.close();
    return ret;
}

bool BundleDataStorage::DeleteStorageModuleInfo(
    const std::string &deviceId, const InnerBundleInfo &innerBundleInfo, const std::string &moduleName) const
{
    return true;
}

猜你喜欢

转载自blog.csdn.net/llffss/article/details/119107152