jsoncpp

来源:互联网 发布:花生壳赠送的免费域名 编辑:程序博客网 时间:2024/05/22 10:40

linux 下的安装需要两个压缩包,分别为scons-2.3.3.tar.gz    jsoncpp-src-0.5.0.tar.gz


一. 安装

  1. 下载上述两个tar文件

  2. 分别解压

  3.  在jsoncpp-src-0.5.0 下执行    python ../scons-2.3.3/script/scons platform=linux-gcc  

        会在当前目录下生成 libs/linux-gcc-3.4.5 目录,该目录下有 libjson_linux-gcc-3.4.5_libmt.a  libjson_linux-gcc-3.4.5_libmt.so  两个库文件

  

二. 使用 

   1.  读取

       a.  json文件 test.json

           

{    "name": "json",    "array": [           "123",        "456",        "789"     ]}

    b .  demo.cpp

         

#include "json/json.h"#include <string>#include <stdlib.h>#include <iostream>#include <fstream>using namespace std;int main(){    ifstream is;    is.open ("test.json", std::ios::binary );     Json::Reader reader;     Json::Value root;     if(reader.parse(is,root))   ///root保存整个Json对象的value     {          if(!root["name"].isNull())          {            cout<<root["name"].asString()<<endl;    ///读取元素            Json::Value arrayObj = root["array"];            for(int i=0 ; i< arrayObj.size() ;i++)            {                cout<<arrayObj[i].asString()<<endl;            }          }     }     return 0;}

c. 编译 

   g++ -o demo demo.cpp -I../include -L../libs/linux-gcc-3.4.5/ -ljson_linux-gcc-3.4.5_libmt

d.  输出

     json
123
456
789


2.  写json文件

    a.   write_json.cpp

         

#include <iostream>#include <string>#include "json/json.h"int main(void){     Json::Value root;     Json::Value arrayObj;     Json::Value item;     for (int i = 0; i < 2; i ++)     {         item["key"] = i;         //arrayObj.append(item);    ///给arrayObj中添加元素(arrayObj变为数组)         arrayObj.append(i);    ///给arrayObj中添加元素(arrayObj变为数组)     }     root["key1"] = "value1";   ///给root中添加属性(arrayObj变为map)     root["key2"] = "value2";     root["array"] = arrayObj;     //root.toStyledString();     std::string out = root.toStyledString();   ///转换为json格式字符串     std::cout << out << std::endl;     return 0;}

  b. 编译同上

  c. 输出

      {
   "array" : [ 0, 1 ],
   "key1" : "value1",
   "key2" : "value2"
}

            

0 0
原创粉丝点击