2014-11-06 33 views
0

代碼:如何模式匹配rapidjson對象?

int main() 
{ 
     char buff[BUFSIZ]; 
     FILE *fp = popen("/usr/bin/php getSome.php 155", "r"); 
     FileReadStream s(fp, buff, BUFSIZ); 
     Document a; 
     a.ParseStream(s); 
     \\for (Value::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr) 
      \\printf("%d ", itr->GetInt()); 
     printf(a[1]); 

} 

我在JSON數據來是這樣的:

./phpMethod1.o 
success:1 
orderid:192877561 
moreinfo:Your Buy order has been placed for<br><b>0.00100000 DRK @ 0.00517290 BTC</b> each.<br>Order ID: <b>192877561</b> 

我試圖獲得「訂單ID」的鍵值。

我已經嘗試了幾乎所有的方法 - >rapidjson user guide來訪問入站json數據,並總是得到相同類型的轉換錯誤。

# g++ -g phpBuyMethod1.cpp -o phpBuyMethod1.o -std=gnu++11 
phpBuyMethod1.cpp: In function 'int main()': 
phpBuyMethod1.cpp:27:13: error: cannot convert 'rapidjson::GenericValue<rapidjson::UTF8<> >' to 'const char*' for argument '1' to 'int printf(const char*, ...)' 

,或者如果我試圖for循環,例如:

for (Value::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr) 
    printf("%d ", itr->GetInt()); 

代碼將編譯,但我會在執行下面的錯誤(基本上窒息同樣的事情):

phpBuyMethod1.o: rapidjson/include/rapidjson/document.h:1167: rapidjson::GenericValue<Encoding, Allocator>* rapidjson::GenericValue<Encoding, Allocator>::Begin() [with Encoding = rapidjson::UTF8<>; Allocator = rapidjson::MemoryPoolAllocator<>; rapidjson::GenericValue<Encoding, Allocator>::ValueIterator = rapidjson::GenericValue<rapidjson::UTF8<> >*; rapidjson::GenericValue<Encoding, Allocator> = rapidjson::GenericValue<rapidjson::UTF8<> >]: Assertion `IsArray()' failed. 

道德是,我只是無法獲得模式匹配的數據。 我該如何正確訪問UTF-8 rapidjson對象併爲'orderid'做模式匹配?

回答

0

您提供的數據不是有效的JSON。有效的JSON類似於:

{ 
"success":1, 
"orderid":192877561, 
"moreinfo":"Your Buy order has been placed for<br><b>0.00100000 DRK @ 0.00517290 BTC</b> each.<br>Order ID: <b>192877561</b>" 
} 

解析應該失敗。您可以通過a.HasParseError()檢查解析是否成功。

此外,在解析上述有效的JSON之後,它的根是一個對象類型,您可以使用a["moreinfo"]來訪問其關聯的值。