【问题标题】:Iterate on json structure with Poco使用 Poco 迭代 json 结构
【发布时间】:2017-12-13 14:28:01
【问题描述】:

我正在为 C++ 代码使用 Poco 库

这是我必须解析的 json 树的示例

{
    "name" : "actionToDo",
    "description" : "",
    "version" : "1",
    "parameters" : {
        "inputDirectory" : "string",
        "workingDir" : "string",
        "tempDir" : "string",
        "size" : "integer"
    }
}

“参数”字段中的数据量可以改变。 我必须将所有项目放入地图中

这是我今天的代码

std:: map<std::string, std::string> output;

Poco::JSON::Parser sparser;
Poco::Dynamic::Var result = sparser.parse(jsonStr);
Poco::JSON::Object::Ptr object = result.extract<Poco::JSON::Object::Ptr>();
Poco::DynamicStruct ds = *object;

Poco::Dynamic::Var collection(ds["parameters"]);

if (collection.isStruct())
{
     LOG("STRUCT"); //it's logged !!
}

for (Poco::Dynamic::VarIterator it = collection.begin(); it != collection.end(); ++it)
{
    LOG_F("item : %s", it->toString()); //never logged
    //here I would like to have something like
    //output[it->first()] = it->second();

}

我得到的输出

14:13:00'900 : : [通知] : STRUCT

14:13:00'900 : : [严重] : 异常 : 异常:无法从文件加载运行: /opt/.../file.json 异常: 无法解析字段“参数”或其子项

无效访问:不是结构。

“无法解析字段 'parameters' 或其子项”是由下面的捕获生成的,但“无效访问:不是结构”。来自Poco

【问题讨论】:

    标签: c++ json dynamic poco-libraries


    【解决方案1】:

    用于collection变量DynamicStruct而不是Var

    Poco::DynamicStruct collection = ds["parameters"].extract<Poco::DynamicStruct>();
    
    for (auto it = collection.begin(); it != collection.end(); ++it)
    {
        LOG_F("item : %s", it->second.toString().c_str());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-19
      • 2011-01-16
      • 2023-03-21
      • 2017-03-29
      • 1970-01-01
      • 2016-12-02
      • 1970-01-01
      相关资源
      最近更新 更多