linux jsoncpp 應用

主要功能有:字符串轉json體,json存配置文件,讀配置文件轉json體,解析各元素



#include <fstream>
#include <stdio.h>
#include <iostream>
#include <string>
#include"../include/json/json.h"
using namespace std;


int main(void)
{
        std::ofstream f1;
        f1.open("json.txt");

       string strJson ="{\"key1\":\"value1\",\"array\":[{\"key2\":\"value2\",\"key3\":\"aa\"},{\"key2\":\"value3\",\"key3\":\"bb\"},{\"key2\":\"value4\",\"key3\":\"cc\"}]}";
       Json::Reader reader;
       Json::StyledWriter styled_writer;
      Json::StyledStreamWriter styled_stream_writer;
         Json::Value val;
        Json::Value val_in;
       if(!reader.parse(strJson,val))
              return-1;


       string str = val["key1"].asString();
       cout<< "key1:" << str << endl;


       Json::Value obj_array = val["array"];
       cout<< styled_writer.write(val) << endl;
        operator<<( f1, styled_writer.write(val));
        f1.close();
//      cout<<styled_stream_writer.writeCommentBeforeValue(obj_array)<<endl;
        std::ifstream f2;
        f2.open("json.txt");
        operator>>(f2,val_in);
        cout<<styled_writer.write(val_in)<<endl;
      for(int i = 0; i < obj_array.size(); i++)
       {
              str= obj_array[i]["key2"].asString();
              cout<< "key2[" << i << "]:" << str<< endl;


              str= obj_array[i]["key3"].asString();
              cout<< "key3[" << i << "]:" << str<< endl;
       }

return 0;

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章