2012-05-16 3 views
2

in this question 표시된 방법을 사용하여 boost::property_tree에서 배열 데이터를 읽으려고합니다. 이 예에서 배열은 먼저 문자열로 읽혀 문자열 스트림으로 변환 된 다음 배열로 읽습니다. 이 솔루션을 구현하는 동안 내 문자열이 비어있는 것으로 나타났습니다.boost :: property_tree에서 배열 읽기가 비어 있습니다.

예 입력 (JSON) : 이러한 배열 표기법의

"Object1" 
{ 
    "param1" : 10.0, 
    "initPos" : 
    { 
    "":1.0, 
    "":2.0, 
    "":5.0 
    }, 
    "initVel" : [ 0.0, 0.0, 0.0 ] 
} 

모두 부스트 JSON 파서에 의해 배열로 해석됩니다. json writer를 호출 할 때 배열 데이터가 출력에 있기 때문에 데이터가 속성 트리에 존재한다고 확신합니다.

이 실패하는 내용의 예입니다 paramName"Object1.param1" 때 나는 paramName"Object1.initPos" 경우 문자열로 "10.0"출력이, 내가 빈 문자열을 얻을 얻을

std::string paramName = "Object1.initPos"; 
tempParamString = _runTree.get<std::string>(paramName,"Not Found"); 
std::cout << "Value: " << tempParamString << std::endl; 

, 경우 paramName은 뭔가 트리에없는 "Not Found"이 반환됩니다.

+0

알 수없는 그것은 관련,하지만 난 부스트 1.49.0을 사용하고있는 경우 – 2NinerRomeo

답변

0

먼저 제공된 JSON이 올바른지 확인하십시오. 거기에 몇 가지 문제가있는 것 같습니다. 다음으로 Object1.initPos를 문자열로 가져올 수 없습니다. 유형은 boost :: property_tree :: ptree입니다. get_child를 사용하여 가져 와서 처리 할 수 ​​있습니다.

#include <algorithm> 
#include <string> 
#include <sstream> 

#include <boost/property_tree/ptree.hpp> 
#include <boost/property_tree/json_parser.hpp> 

using namespace std; 
using namespace boost::property_tree; 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    try 
    { 
     std::string j("{ \"Object1\" : { \"param1\" : 10.0, \"initPos\" : { \"\":1.0, \"\":2.0, \"\":5.0 }, \"initVel\" : [ 0.0, 0.0, 0.0 ] } }"); 
     std::istringstream iss(j); 

     ptree pt; 
     json_parser::read_json(iss, pt); 

     auto s = pt.get<std::string>("Object1.param1"); 
     cout << s << endl; // 10 

     ptree& pos = pt.get_child("Object1.initPos"); 
     std::for_each(std::begin(pos), std::end(pos), [](ptree::value_type& kv) { 
      cout << "K: " << kv.first << endl; 
      cout << "V: " << kv.second.get<std::string>("") << endl; 
     }); 
    } 
    catch(std::exception& ex) 
    { 
     std::cout << "ERR:" << ex.what() << endl; 
    } 

    return 0; 
} 

출력 :

10.0 
K: 
V: 1.0 
K: 
V: 2.0 
K: 
V: 5.0