2012-08-10 25 views
1

我需要了解和修改示例代碼。我被困在某一點,找不到任何解決方案。這裏是代碼:我們如何獲得增強屬性樹中的對象

void foo(std::istream& input) 
{ 
    using boost::property_tree::ptree; 
    ptree pt; 

    boost::property_tree::read_json(input, pt); 

    BOOST_FOREACH(ptree::value_type &node, pt.get_child("some_nodes")) 
    { 
     std::string id; 
     unsigned int number1; 
     bool flag1; 
     bool flag2; 

     id = node.second.get<std::string>("id"); 
     number1 = node.second.get<unsigned int>("number1"); 
     flag1 = node.second.get<bool>("flag1"); 
     flag2 = node.second.get<bool>("flag2"); 
    } 
} 

有人可以告訴我'第二'是什麼意思嗎?

這裏是JSON例子程序讀取:

{ 
    "some_nodes" : 
    [ 
      { 
        "id"   : "vader", 
        "number1"  : "1024", 
        "flag1"  : "false", 
        "flag2"  : "true", 
      }, 
      { 
        "id"   : "anakin", 
        "number1"  : "4096", 
        "flag1"  : "true", 
        "flag2"  : "true",  
      } 
    ] 
} 

還有一個問題,我還當我嘗試編譯代碼碰到下面的錯誤。這是什麼意思,我該如何解決它?

Invalid arguments ' 
Candidates are: 
boost::foreach_detail_::foreach_reference<#0,#1>::type deref(const boost::foreach_detail_::auto_any_base &, boost::foreach_detail_::type2type<#0,#1> *) 
' 

非常感謝。

+0

這將有助於發佈一個xml/json /無論這段代碼讀取的例子。 – 2012-08-10 12:55:29

+0

加入帖子.. – minyatur 2012-08-10 12:56:46

回答

1

ptree中:: value_type的定義是這樣的:

typedef std::pair< const Key, self_type > value_type; 

所以它只是一個std ::對。 你的JSON的根節點是數組「some_nodes」。 當你迭代你的屬性樹時,你遍歷所有的「some_nodes」子元素。

  • 第一場是關鍵(在這種情況下,因爲你迭代所有根的子節點隱含的)。我想你的情況node.first總是「some_nodes」。
  • 第二個是值(密鑰的子節點:另一個ptree)。在這種情況下,在每次迭代中,第二個是數組的第i個未命名對象。
+0

哦,現在有道理!非常感謝你.. – minyatur 2012-08-10 13:19:11

+0

我不熟悉JSON,所以我希望我說的是對的。我只用它與XML。在每個級別,第一個元素是父節點,第二個元素是它的一個子節點。 – Heisenbug 2012-08-10 13:21:46

+0

是的,它對我來說也是有意義的。 – minyatur 2012-08-10 13:50:11

相關問題