json/dynamic(动态数据类型)处理

#include <folly/dynamic.h>
#include <folly/json.h>
  • 案例
std::make_unique<folly::dynamic> content_;

Status Configuration::parseFromString(const std::string &content) {
    try {
        auto json = folly::parseJson(content);
        content_ = std::make_unique<folly::dynamic>(std::move(json));
    } catch (std::exception &e) {
        LOG(ERROR) << e.what();
        return Status::Error("Illegal format (%s)", e.what());
    }
    return Status::OK();
}

Status Configuration::forEachKey(std::function<void(const std::string&)> processor) const {
    DCHECK(content_ != nullptr);
    for (auto& key : content_->keys()) {
        try {
            processor(key.asString());
        } catch (const std::exception& ex) {
            // Avoid format sercure by literal
            return Status::Error("%s", ex.what());
        }
    }
    return Status::OK();
}


Status Configuration::forEachItem(
        std::function<void(const std::string&, const folly::dynamic&)> processor) const {
    DCHECK(content_ != nullptr);
    for (auto& item : content_->items()) {
        try {
            processor(item.first.asString(), item.second);
        } catch (const std::exception& ex) {
            // Avoid format sercure by literal
            return Status::Error("%s", ex.what());
        }
    }
    return Status::OK();
}

推荐阅读更多精彩内容