jsoncpp

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值