JsonCpp使用简介

一、 JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,和xml类似。

JSON 名称/值对 例如 "firstName" : "John"
 JSON 对象在花括号中书写,例如  { "firstName":"John","lastName":"Doe" }
 JSON 数组,数组可包含多个对象  
 {"employees": [{ "firstName":"John","lastName":"Doe" },{ "firstName":"Anna","lastName":"Smith" },]}

Jsoncpp
Json::Value 是jsoncpp 中最基本、最重要的类,用于表示各种类型的对象,
Json::Reader 用来将内存或文件中的json数据转换成Json::Value类型
Json::Writer 用来将Json::Value类型转换成内存或文件中的json数据

二、Jsoncpp环境搭建

下载地址 https://github.com/open-source-parsers/jsoncpp
下载完成后,解压,将include\json和src\lib_json目录里的文件包含到C++工程中与其他源码一起编译即可。
如在Qt中,新建non-qt c++工程,然后右键add exiting directory,将json以及lib_json都添加到到工程当中。

三、使用Jsoncpp读取内存中的json数据

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

int main(int argc,char *argv[])
{
    const char* str = "{\"name0\": \"helloworld\",\"name1\": 100,\"name2\": 200.0,\"name3\": true}";

    Json::Reader reader;
    Json::Value root;

    /*reader将Json字符串解析到root,root将包含Json里所有对象*/
    if (!reader.parse(str,root))
    {
        cout<<"reader parse error"<<endl;
        return -1;
    }
    //Json::Value类型可以直接使用cout打印出来
    cout << "json : "<< endl << root << endl;

    string name0 = root["name0"].asstring();  // 访问值对,name0= "helloworld"
    cout << "name0 : "<< name0 << endl;

    int name1 = root["name1"].asInt();    // 访问值对,name1 = 100
    cout << "name1 : "<< name1 << endl;


    double name2 = root["name2"].asDouble();  // 访问值对,name2 = "200.0"
    cout << "name2 : "<< name2 << endl;

    bool name3 = root["name3"].asBool();  // 访问值对 name3 = true
    cout << "name3 : "<< name3 << endl;

    int name4 = root.get("name4",20).asInt();   //访问值对 name4 如果不存在就返回认值20,没有写入root当中.
    cout << "name4 : "<< name4 << endl;

    cout << "json : "<< endl << root << endl;
    return 0;
}

四、使用Jsoncpp读取json文件添加新的值对,删除值对,并且写入json文件

在c盘创建test.json
----------------------------
{
"name0": "helloworld","name1": 100,"name2": 200.0,"name3": true
}
----------------------------

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

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

    Json::Reader reader;
    Json::Value root;

    std::ifstream ifs;
    ifs.open ("c:/test.json");
    if(!ifs.is_open())
    {
       cout<<"not open test.json"<<endl;
       return false;

    }

    if (!reader.parse(ifs,root))
    {
       cout<<"reader parse error"<<endl;
       return -1;
    }

    cout<<root<<endl;
    root["name4"] = Json::Value("hellword2"); //添加新值对
    root["name5"] = Json::Value(300);
    root["name6"] = Json::Value(400.123);
    root["name7"] = Json::Value(true);
    cout<<root<<endl;

    root["name4"] = Json::Value("hellword3"); //如果已经存在,则修改值对内容
    root["name5"] = Json::Value(500);
    root["name6"] = Json::Value(600.123);
    root["name7"] = Json::Value(false);
    cout<<root<<endl;

    root.removeMember("name6");
    root.removeMember("name7");
    cout<<root<<endl;

    Json::FastWriter writer;
    string strWrite = writer.write(root);  

    ifs.close();           //先把test.json文件关闭
    std::ofstream ofs;     //通过ofstream把root写入json文件
    ofs.open("c:/test.json");
    ofs << strWrite;
    ofs.close();

    return 0;
}

五、读取json中的数组,并且修改数组中的值对

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

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

    const char* str = "{\"name0\": 100,"
                      "\"name1\": "
                      "[ {\"age\": 20},{\"age\":23}]"
                      "}";
    Json::Reader reader;
    Json::Value root;

    if (!reader.parse(str,root))
    {
       cout<<"reader parse error"<<endl;
       return -1;
    }
    cout<<root<<endl;

    Json::Value &name1_Value = root["name1"];
    int file_size = name1_Value.size(); //获取数组name1的数组大小

    cout<<"file_size = "<<file_size<<endl;
    for(int i=0; i<file_size; i++)  //遍历所有数组中的age值对
    {
        cout<<"name1:"<<i<<": age:"<< name1_Value[i]["age"].asInt() <<endl;
        name1_Value[i]["age"] = Json::Value(100);//并且修改值对
    }

    cout<<root<<endl;


    return 0;
}

六、根节点创建数组,在数组中插入Json::Value对象

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

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

    const char* str = "{\"name0\": 100}";
    Json::Reader reader;
    Json::Value root;

    if (!reader.parse(str,root))
    {
       cout<<"reader parse error"<<endl;
       return -1;
    }

    root["name1"].removeIndex(0);
    cout<<root<<endl;


    Json::Value item0;
    item0["age"] = 23;
    item0["male"] = true;
    root["name1"].append(item0);//添加一个对象
    cout<<root<<endl;
/* Json::Value item1; item1["age"] = 24; item1["male"] = false; root["name1"].append(item1);//再添加一个对象 cout<<root<<endl; */

    return 0;
}

相关文章

AJAX是一种基于JavaScript和XML的技术,能够使网页实现异步交...
在网页开发中,我们常常需要通过Ajax从后端获取数据并在页面...
在前端开发中,经常需要循环JSON对象数组进行数据操作。使用...
AJAX(Asynchronous JavaScript and XML)是一种用于创建 We...
AJAX技术被广泛应用于现代Web开发,它可以在无需重新加载页面...
Ajax是一种通过JavaScript和HTTP请求交互的技术,可以实现无...