2012-04-23 20 views
0

プログラムを正常にコンパイルできましたが、jsonオブジェクトから値を取得できませんでした。私は以下のコードを貼り付けています、コードはシンプルです、どんな助けにも感謝します。json_spirit使用上の問題

#include <cstdio> 
#include <cstring> 
#include <json_spirit.h> 

using namespace std; 
using namespace json_spirit; 

//A sample get file request 
char *jsonInput = 
"{\"request\" : { \ 
       \"service\" : \"fmgr\" \ 
       \"cookie\" : \"Abxruyyeziyrolsu\" \ 
       \"req\"  : \"read\" \ 
       \"fname\" : \"Junk.txt\" \ 
       \"size\" : 1024 \ 
       \"data\" : \"data\" \ 
}}"; 


int main(int argc, char **argv) 
{ 
    Value val; 
    const string s = jsonInput; 
    read(s, val); //read the jsonInput to the value 
    Object obj = val.get_obj(); 
    std::string service, cookie, req, fname, data; 
    uint32_t size; 

    for(Object::size_type i = 0; i != obj.size(); ++i) { 
     const Pair& pair = obj[i]; 
     const string& name = pair.name_; 
     const Value& value = pair.value_; 

     if(name == "service") service = value.get_str(); 
     else if(name == "cookie") cookie = value.get_str(); 
     else if(name == "req") req = value.get_str(); 
     else if(name == "fname") fname = value.get_str(); 
     else if(name == "size") size = value.get_int(); 
     else if(name == "data") data = value.get_str(); 
    } 
    std::cout<<service << " " << cookie << " " << req << " " << fname << " " << size << " " << data ; 
    return 0; 
} 

答えて

0

二つの問題があります。

  1. jsonInput文字列が有効なJSONではない、別のオブジェクトのペアにカンマが欠落しています。
  2. 次の問題は説明がより複雑です。トップレベルValueはそれ自身Objectですので、val.get_obj()を呼び出すと、すべてのデータを含むObjectが返されます。このオブジェクトには「要求」という名前のペアが1つしかありません。 val.get_obj()[0]を呼び出すと、このペアが取得されます。次に、このペアの値からオブジェクトを取得する必要があります。

    値val; read(s、val); // jsonInputを値に読み取る

    constペア&ペア= val.get_obj()[0]; //名前:値のペアを取得し、「request」という名前を取得します。

    constオブジェクト& obj = pair.value_.get_obj(); //、

0

は物事をシンプルに保つために、オブジェクト、彼らはjson_spiritであるべきとして、JSON文字列に欠落している「」区切り文字を修正した後、以下を試してみてください...サービス、クッキーを取得します。

std::string json_input = <your valid JSON string> 
json_spirit::Value value; 
auto success = json_spirit::read_string(json_input, value); 
if (success == true) { 
    auto object = value.get_obj(); 
    for (auto entry : object) { 
     if (entry.name_ == "service") service = entry.value_.get_str(); 
     else if... 
     . 
     . 
    } 
} 
関連する問題