cpp的json的用法舉例

zh515858237發表於2016-06-13

#include "json/json.h"

#include <string>

#include <iostream>

#include <fstream>

using namespace std;

const string movie = "電影";

const string cartoon = "動漫";

const string tvplay = "電視";

const string variety = "綜藝";

void getValue(string key, string property, Json::Value value){

    Json::Value arrayObj = value[key.c_str()];

    if(arrayObj.size() != 0){

        for (unsigned int i = 0; i < arrayObj.size(); i++)

        { 

            string tmp = arrayObj[i][property.c_str()].asString();

            std::cout << tmp << "\t";

        } 

        std::cout << std::endl;

    }

}

void printHelp(){

    cout << "a.out movie|cartoon|tvplay|variety" << endl;

}

int main(int argc, char* argv[])

{

    if(argc != 2){

        cerr << "param count is "<< argc << endl;

        printHelp();

        return -1;

    }


    string query = argv[1];

    if(query.compare("movie") != 0 && query.compare("cartoon") != 0 &&

            query.compare("tvplay") != 0 && query.compare("variety") != 0

      ){

        cerr << "second param is "<< argv[1] << endl;

        printHelp();

        return -1;

    }

    if(query.compare("movie") == 0)     query = "電影";

    if(query.compare("cartoon") == 0)   query = "動漫";

    if(query.compare("tvplay") == 0)    query = "電視";

    if(query.compare("variety") == 0)   query = "綜藝";


    Json::Reader reader;

    Json::Value value;

    string file_name = "total.dat"

    ifstream infile(file_name.c_str(),ios::in);

    string textline; 

    bool needInfo = false;

    int count_line = 0;

    int count_query = 0;


    while(getline(infile, textline, '\n')){

        needInfo = false;

        count_line++;

        if(reader.parse(textline, value)){

            Json::Value arrayObj = value["domain"];

            for (unsigned int i = 0; i < arrayObj.size(); i++){ 

                string domain = arrayObj[i]["@value"].asString();

                if (domain.compare(query) == 0) {

                    needInfo = true;

                    break;

                }

            } 


            if(needInfo == true){

                getValue("@uri", "@value", value);

            }

        }

    }

    return 0;

}

相關文章