2017-07-11 132 views
1

我有一個JSON與嵌套的對象(這是一個製作的例子,因爲真正的JSON更大和更復雜)。我需要通過siblings對象進行迭代。我知道如何處理數組,但找不到任何示例來處理這種嵌套對象(任何嵌套深度)。Poco迭代嵌套的JSON對象

任何想法是讚賞。

{ 
    ....... 
    "siblings":{ 
     "Michael":{ 
      "age":20, 
      "lives":"Dodoma" 
     }, 
     "Polyasi":{ 
      "age":25, 
      "lives":"Geita" 
     }, 
     "Kiah":{ 
      "age":3, 
      "lives":"Dar es Salaam" 
     } 
    } 
    ........... 
} 
+0

查找(https://pocoproject.org/docs/Poco.JSON.Object.html)。它看起來像遍歷一個'std :: map'一樣。 – Alex

+0

我假設你引用'ValueMap :: iterator'。 AFAIK,它是爲了價值。現在我不確定是否覆蓋了像我這種情況下的對象,以及如何將值轉換爲Poco :: JSON :: Object。 –

+0

我想會更好的發佈輸入json和預期結果的完整示例。 –

回答

1

所以我發現,ValueMap ::迭代器並不關心它是否是它會將它們同一個對象或原子值。所以這裏是我創造的一個實際測試的例子。感謝@atomic_alarm讓我嘗試了一些我已經放棄的解決方案。

packagist.json實際上被重命名爲JSON文件here。這是代碼。確保你鏈接到基礎和json庫。

#include <Poco/JSON/Parser.h> 
#include <Poco/Dynamic/Var.h> 
#include <string> 
#include <fstream> 
#include <streambuf> 
#include <iostream> 

void print_version_names(Poco::JSON::Object::Ptr root); 

int main(int argc, char** argv) 
{ 
    //read file 
    std::ifstream t("packagist.json"); 
    std::string json_str((std::istreambuf_iterator<char>(t)), 
       std::istreambuf_iterator<char>()); 

    Poco::JSON::Parser parser; 
    Poco::Dynamic::Var result = parser.parse(json_str); 
    Poco::JSON::Object::Ptr json = result.extract<Poco::JSON::Object::Ptr>(); 

    print_version_names(json); 

    return 0; 
} 

void print_version_names(Poco::JSON::Object::Ptr root) 
{ 
    std::string root_key = "package"; 
    std::string key = "versions"; 
    //no checks whether such key acually exists 
    Poco::JSON::Object::Ptr package_json = root->getObject(root_key); 
    //get the nested objects 
    Poco::JSON::Object::Ptr nested_versions = package_json->getObject(key); 

    //iterate the map 
    Poco::JSON::Object::Iterator it; 
    for(it = nested_versions->begin(); it != nested_versions->end(); it++) 
    { 
     //no check of whether it is an object 
     std::cout<<it->first<<"\n"; 
    } 
} 

結果:在[文檔對象]

2.0.0 
2.0.0-alpha 
2.0.0-beta 
2.0.0-rc 
2.0.1 
2.0.10 
2.0.11 
2.0.11.1 
2.0.11.2 
2.0.12 
2.0.2 
2.0.3 
2.0.4 
2.0.5 
2.0.6 
2.0.7 
2.0.8 
2.0.9